link
简介
<link>
标签主要用于将当前网页与相关的外部资源联系起来,通常放在<head>
元素里面。最常见的用途就是加载 CSS 样式表。
<link rel="stylesheet" type="text/css" href="theme.css">
上面代码为网页加载样式表theme.css
。
除了默认样式表,网页还可以加载替代样式表,即默认不生效、需要用户手动切换的样式表。
<link href="default.css" rel="stylesheet" title="Default Style">
<link href="fancy.css" rel="alternate stylesheet" title="Fancy">
<link href="basic.css" rel="alternate stylesheet" title="Basic">
上面代码中,default.css
是默认样式表,默认就会生效。fancy.css
和basic.css
是替换样式表(rel="alternate stylesheet"
),默认不生效。title
属性在这 里是必需的,用来在浏览器菜单里面列出这些样式表的名字,供用户选择,以替代默认样式表。
<link>
还可以加载网站的 favicon 图标文件。
<link rel="icon" href="/favicon.ico" type="image/x-icon">
手机访问时,网站通常需要提供不同分辨率的图标文件。
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="favicon114.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="favicon72.png">
上面代码指定 iPhone 设备需要的114像素和72像素的图标。
<link>
也用于提供文档的相关链接,比如下面是给出文档的 RSS Feed 地址。
<link rel="alternate" type="application/atom+xml" href="/blog/news/atom">
href 属性
href
属性表示<link>
标签所链接的资源。
rel 属性
rel
属性表示外部资源与当前文档之间的关系,是<link>
标签的必需属性,可以视为对href
属性所链接资源的说明。
它可以但不限于取以下值。
alternate
:文档的另一种表现形式的链接,比如打印版。author
:文档作者的链接。dns-prefetch
:要求浏览器提前执行指定网址的 DNS 查询。help
:帮助文档的链接。icon
:加载文档的图标文件。license
:许可证链接。next
:系列文档下一篇的链接。pingback
:接收当前文档 pingback 请求的网址。preconnect
:要求浏览器提前与给定服务器,建立 HTTP 连接。prefetch
:要求浏览器提前下载并缓存指定资源,供下一个页面使用。它的优先级较低,浏览器可以不下载。preload
:要求浏览器提前下载并缓存指定资源,当前页面稍后就会用到。它的优先级较高,浏览器必须立即下载。prerender
:要求浏览器提前渲染指定链接。这样的话,用户稍后打开该链接,就会立刻显示,感觉非常 快。prev
:表示当前文档是系列文档的一篇,这里给出上一篇文档的链接。search
:提供当前网页的搜索链接。stylesheet
:加载一张样式表。
下面是一些示例。
<!-- 作者信息 -->
<link rel="author" href="humans.txt">
<!-- 版权信息 -->
<link rel="license" href="copyright.html">
<!-- 另一个语言的版本 -->
<link rel="alternate" href="https://es.example.com/" hreflang="es">
<!-- 联系方式 -->
<link rel="me" href="https://google.com/profiles/someone" type="text/html">
<link rel="me" href="mailto:name@example.com">
<link rel="me" href="sms:+15035550125">
<!-- 历史资料 -->
<link rel="archives" href="http://example.com/archives/">
<!-- 目录 -->
<link rel="index" href="http://example.com/article/">
<!-- 导航 -->
<link rel="first" href="http://example.com/article/">
<link rel="last" href="http://example.com/article/?page=42">
<link rel="prev" href="http://example.com/article/?page=1">
<link rel="next" href="http://example.com/article/?page=3">
hreflang 属性
hreflang
属性用来表示href
属性链接资源的所用语言,通常指当前页面的其他语言版本。
<link href="https://example.com/de" rel="alternate" hreflang="de" />
上面示例中,hreflang
表示href
属性所链接页面使用德语,即当前页面的德语版本。
如果一个页面有多个语言的版本,hreflang
属性可以设为x-default
,表示哪一个页面是默认版本。
<link href="https://example.com" rel="alternate" hreflang="x-default" />
<link href="https://example.com/de" rel="alternate" hreflang="de" />
上面示例中,hreflang
设为x-default
表示该页面为默认版本。