<h1>所有网站通用:6 行 HTML 代码搞定页面加载提速</h1>
<script type="speculationrules">
{
"prerender": [{ "where": { "href_matches": "/*" }, "eagerness": "moderate" }],
"prefetch": [{ "where": { "href_matches": "/*" }, "eagerness": "moderate" }]
}
</script>
把这段 HTML 标签塞进你网站的 “ 里,就能实现近乎瞬间的页面跳转体验!
有没有过这种感觉:点个链接,下一页“唰”地就出来了?这种神奇的秒开体验,现在靠 Chrome 的推测规则 API(Speculation Rules API) 就能轻松实现。这个全新的浏览器特性,只用几行 HTML 就能让页面导航快到飞起。
它是怎么干活的?
Chrome 的推测规则 API 允许开发者“ declaratively ”(也就是用配置的方式)告诉浏览器该预加载或预渲染哪些页面,从而实现近乎瞬间的加载效果:
"prefetch"
****(预获取):只让浏览器下载目标页面的顶层 HTML 文件,不渲染页面,也不加载 CSS、JS、图片这些子资源。虽然比预渲染省资源,但提前把 HTML 缓存好,也能省不少加载时间。"prerender"
****(预渲染):不仅会下载页面,还会在后台完整渲染——包括拉取所有子资源、执行 JavaScript。等用户真点了链接,直接把后台渲染好的页面“切换”到前台,简直瞬间完成。"eagerness": "moderate"
:浏览器会这么理解:“等用户把鼠标悬停在链接上 200 毫秒后,我再开始干活”(避免误触时白忙活)。
举个真实场景看看
- 用户正在看你网站的某个页面;
- 他们把鼠标移到“服务”这个链接上,停了一下;
- 浏览器捕捉到这个“想点”的信号,等 200 毫秒(确认不是手滑)后,就开始预渲染或预获取“服务”页面;
- 要是用户真点了链接——页面早就准备好了,秒开!
我们 Docuseal 之前是用 Hotwired Turbo 来实现类 SPA 的导航效果,以及 hover 时预加载页面。现在换成推测规则后,不仅删掉了 Turbo 的依赖,还能通过预渲染让重型页面加载更快。
有啥限制?
推测规则 API 目前只支持 Chrome 121 及以上版本。其他浏览器的支持情况看这里:
Chrome | Edge | Safari | Firefox | Opera | IE | Chrome for Android | Safari on iOS | Samsung Internet |
---|---|---|---|---|---|---|---|---|
4-120 | 12-120 | – | 2-140 | 10-106 | – | – | – | 4-24 |
121-137 | 121-137 | 3.1-18.4 | – | 107-116 | 6-10 | – | 3.2-18.4 | 25-27 |
138 | 138 | 18.5 | 141 | 117 | 11 | 138 | 18.5 | 28 |
139-141 | – | 26.0-TP | 142-144 | – | – | – | 26.0 | – |
针对 Firefox 和 Safari 用户,我们写了个简短的降级脚本——hover 时预加载页面,让浏览器缓存起来,点链接时直接复用。这样就算不支持推测规则 API,也能接近秒开。不过比起 Chrome 的预渲染,这些浏览器的重型页面(比如 API 文档页)加载还是会慢一点,毕竟没有原生预渲染加持。
降级脚本在这里:
if (!HTMLScriptElement.supports || !HTMLScriptElement.supports('speculationrules')) {
const preloadedUrls = {};
function pointerenterHandler () {
if (!preloadedUrls[this.href]) {
preloadedUrls[this.href] = true;
const prefetcher = document.createElement('link');
prefetcher.as = prefetcher.relList.supports('prefetch') ? 'document' : 'fetch';
prefetcher.rel = prefetcher.relList.supports('prefetch') ? 'prefetch' : 'preload';
prefetcher.href = this.href;
document.head.appendChild(prefetcher);
}
}
document.querySelectorAll('a[href^="/"]').forEach(item => {
item.addEventListener('pointerenter', pointerenterHandler);
});
}
要让这个脚本在 Firefox 和 Safari 上生效,你的页面得加一个 Cache-Control
响应头,并且设置 max-age
值——这样 hover 时预加载的页面才能被缓存,点链接时直接复用。
</div>
未经允许不得转载:紫竹林-程序员中文网 » 所有网站通用:6 行 HTML 代码搞定页面加载提速