Playing with the Speculation Rules API in the Console
将 Speculation Rules API 应用到 WordPress 博客,过程包括:
加载一个网页,如 https://phpied.com
。
打开浏览器控制台,为三个链接添加类名 prerenderosa
:
document.querySelectorAll('.entry a[rel=bookmark]')
.slice(0, 3)
.forEach(e => e.classList.add('prerenderosa'));
设置 speculation rules 的 JavaScript 对象:
const pre = {
"prerender": [{
"source": "document", // 可选
"where": {
"and": [
{ "selector_matches": ".prerenderosa" },
]
},
"eagerness": "immediate", // 迫不及待
}]
};
将 speculation rules 添加到页面:
const spec = document.createElement('script');
spec.type = "speculationrules";
spec.append(JSON.stringify(pre));
document.body.append(spec);
文章详细介绍了如何在浏览器控制台中使用 Speculation Rules API 提前加载页面,从而提高网页响应速度。这种方法不仅能有效提升用户体验,还提供了一系列调试和配置选项,帮助开发者更好地掌控预加载过程。新的 API 具备广泛的应用前景,非常值得探索和测试。