link
标签。rel
属性确定类型,href
属性则指定相应的源或资源URL。DNS Prefetch可以像下面这样使用:rel
属性设为preconnect
即可:as
的可选属性,用来指定获取资源的类型。由于不同的资源类型会具有不同的优先级、CSP、请求头等,因此该属性很重要。下表列出了一些常用资源的as
属性值:<audio>
<link rel=preload as=audio href=...>
<video>
<link rel=preload as=video href=...>
<track>
<link rel=preload as=track href=...>
<script>
, Worker's importScripts<link rel=preload as=script href=...>
<link rel=stylesheet>
, CSS @import<link rel=preload as=style href=...>
<link rel=preload as=font href=...>
<img>
, <picture>
, srcset, imageset<link rel=preload as=image href=...>
<image>
, CSS *-image<link rel=preload as=image href=...>
<link rel=preload as=fetch crossorigin href=...>
<link rel=preload as=worker href=...>
<embed>
<link rel=preload as=embed href=...>
<object>
<link rel=preload as=object href=...>
<iframe>
, <frame>
<link rel=preload as=document href=...>
<link rel=preload as=html href=...>
script
和style
,甚至还包括XHR、video、img等,基本涵盖了Web中的各类资源。为了解决Prefetch中某些资源(例如XHR)的跨域问题,可以为其应用CORS属性。一个基本的Prefetch写法也很简单:<script>
、<style>
等页面所需资源也可能会被处理。但是预处理会由于浏览器或当前机器、网络情况的不同而被不同程度地推迟。例如,会根据CPU、GPU和内存的使用情况,以及请求操作的幂等性而选择不同的策略或阻止该操作。visibilitychange
事件并使用document.visibilityState
来判断页面状态。When prerendering a document the user agent MUST set the document's visibilityState value to prerender. —— W3C Working Draft
rel
属性为prerender
:link
中使用它们。然而除了直接在HTML中加入对应link
标签外,还可以通过其他几种方式触发浏览器的Resource Hint。为了更加直观,下面我们还是以图书搜索这个demo为例来看看可以通过哪些方法来使用Resource Hint。假设已经为该demo添加详情页nextpage.html
及其依赖的nextpage.js
,当点击列表中的图书时会进行跳转。
nextpage.js
脚本可以这么写:The Link entity-header field provides a means for serialising one or more links in HTTP headers. It is semantically equivalent to the element in HTML, as well as the atom:link feed-level element in Atom. —— RFC5988
Link
主要由两部分组成——URI-Reference
和link-param
。URI-Reference
相当于link
元素中的href
属性;link-param
则包括了rel
、title
、type
等一系列元素属性,使用;
分割。因此可以在响应头中添加以下部分:index.html
时,浏览器就会向服务器请求nextpage.js
这个页面本身并“不需要”用到的资源。link
元素也支持我们通过js动态向文档添加。对于动态添加的RHL,浏览器也会对其应用Resource Hint策略。添加link
的方式和添加普通dom元素一致。href
属性(或者prefetch时的as
属性)时,会立即触发对新资源的Resource Hint。例如在如下代码执行后the.other.nextpage.js
这个资源。注意,当你修改as
属性时,也会触发Resource Hint。link
元素预获取nextpage.html
这个资源,然后像下面这样写会触发两次请求。(Preload) Initiating an early fetch and separating fetching from resource execution.
nextpage.js
,然后获取并执行current.js
,最后,遇到使用nextpage.js
资源的script
标签时,将已经获取的nextpage.js
执行。由于我们会将script
标签置于body底部来保证性能,因此可以考虑在head标签中添加这些资源的Preload来加速页面的加载与渲染。The application can use the preload keyword to initiate early, high-priority, and non-render-blocking fetch of a CSS resource that can then be applied by the application at appropriate time
PWA本身其实是一个概念集合,它不是指某一项技术,而是通过一系列的Web技术与Web标准来优化Web App的安全、性能和体验。