声明:此文带着本身的理解,不彻底按原文翻译,原文地址css
prefetch 即预加载,在用户须要前咱们就将所需的资源加载完毕。html
如今的 chrome 聪明到根据你的浏览记录,预测到你可能访问或搜索哪些网站,在你打开网站以前就加载好了一些资源了。
举个栗子,当你在搜索框输入 "amaz" 时,它猜想到你可能要访问 amazon.com,可能就帮你加载了这个网站的一些资源。
若是这个预测算法精准的话,就能大大地提升用户的浏览体验了。html5
咱们知道,当咱们访问一个网站如 www.amazon.com 时,须要将这个域名先转化为对应的 IP 地址,这是一个很是耗时的过程。ajax
DNS prefetch 分析这个页面须要的资源所在的域名,浏览器空闲时提早将这些域名转化为 IP 地址,真正请求资源时就避免了上述这个过程的时间。算法
<meta http-equiv='x-dns-prefetch-control' content='on'> <link rel='dns-prefetch' href='http://g-ecx.images-amazon.com'> <link rel='dns-prefetch' href='http://z-ecx.images-amazon.com'> <link rel='dns-prefetch' href='http://ecx.images-amazon.com'> <link rel='dns-prefetch' href='http://completion.amazon.com'> <link rel='dns-prefetch' href='http://fls-na.amazon.com'>
应用场景1:咱们的资源存在在不一样的 CDN 中,那提早声明好这些资源的域名,就能够节省请求发生时产生的域名解析的时间。
应用场景2:若是咱们知道用户接下来的操做必定会发起一块儿资源的请求,那就能够将这个资源进行 DNS-Prefetch,增强用户体验。chrome
在 Chrome 下,咱们能够用 link标签声明特定文件的预加载:浏览器
<link rel='subresource' href='critical.js'> <link rel='subresource' href='main.css'> <link rel='prefetch' href='secondary.js'>
在 Firefox 中或用 meta 标签声明:缓存
<meta http-equiv="Link" content="<critical.js>; rel=prefetch">
rel='subresource' 表示当前页面必须加载的资源,应该放到页面最顶端先加载,有最高的优先级。app
rel='prefetch' 表示当 subresource 全部资源都加载完后,开始预加载这里指定的资源,有最低的优先级。工具
注意:只有可缓存的资源才进行预加载,不然浪费资源!
前面说到的预解析DNS、预加载资源已经够强悍了有木有,可还有更厉害的预渲染(Pre-rendering)!
预渲染意味着咱们提早加载好用户即将访问的下一个页面,不然进行预渲染这个页面将浪费资源,慎用!
<link rel='prerender' href='http://www.pagetoprerender.com'>
rel='prerender' 表示浏览器会帮咱们渲染但隐藏指定的页面,一旦咱们访问这个页面,则秒开了!
在 Firefox 中或用 rel='next' 来声明
<link rel="next" href="http://www.pagetoprerender.com">
当资源为如下列表中的资源时,将阻止预渲染操做:
在 head 中强势插入 link[rel='prerender'] 便可:
var hint =document.createElement("link") hint.setAttribute(“rel”,”prerender”) hint.setAttribute(“href”,”next-page.html”) document.getElementsByTagName(“head”)[0].appendChild(hint)
这么好用的特性,固然要考虑各浏览器的兼容程度了(哭:
IE9 支持 DNS pre-fetching 但管它叫 prefetch。
IE10+ 中 dns-prefetch 和 prefetch 是等价的。
其余方面的测试,目前尚未很好的方案,暂且只能经过查看浏览器是否缓存来测试。
在 Chrome 中打开了 chrome developer tools 开发工具会阻止页面的预渲染,因此咱们看不到这个过程,但能够在 chrome://cache/ 或 chrome://net-internals/#prerender 中查看。
Firefox 能够在 about:cache 中查看。
这些特定仍是实验性质的,未来可能改变。
权利越大,责任越大,不要滥用!