使用‌Speculation Rules API‌ 加速网页

教程

使用‌Speculation Rules API‌ 加速网页

2026-03-20/0/ 编辑


代码

<script id="speculation-rules" type="speculationrules">
{"prefetch":[{"where":{"href_matches":"/*"},"eagerness":"moderate"}]}
</script>

‌Speculation Rules API‌ 是由 Google 提出并由 Chromium 内核浏览器(如 Chrome、Edge)支持的一种‌原生网页预加载技术‌,通过声明式 JSON 配置,让浏览器在用户尚未点击链接前,就提前下载甚至完整渲染目标页面,从而实现“点击即现”的极致体验。

核心功能与模式

‌prefetch(预取)‌
提前下载目标页面的 HTML、CSS、JS 等资源至 HTTP 缓存,‌不执行脚本或渲染页面‌。资源消耗低,适合全站兜底使用。

‌prerender(预渲染)‌
在后台‌完整加载并运行页面‌,包括执行脚本、发起请求、渲染布局。点击时几乎瞬间切换,但消耗较多 CPU、内存和网络资源,需谨慎使用。

触发时机(eagerness 参数)

触发条件适用场景
immediate发现规则即开始非常确定用户会访问(如“下一步”按钮)
eager页面空闲时快速启动在移动设备上,eager 会在锚点进入视口后 ‌50 毫秒‌触发;在桌面端,则是‌指针悬停 10 毫秒‌即触发
moderate(默认)悬停 200ms 或聚焦时触发‌最常用平衡方案‌
conservative鼠标按下(mousedown)才触发资源受限或敏感操作

基于以上原理

我这样提取除了某个元素下的链接构成白名单

<script id="speculation-rules" type="speculationrules">{"prefetch":[]}</script>
<script>
// 等待页面加载完成,确保能获取到 .aside 元素
document.addEventListener(\'DOMContentLoaded\', function() {
  // 1. 获取 .aside 内所有的链接 href
 const asideLinks = Array.from(document.querySelectorAll(\'.aside a\'))
    .map(link => link.href) // 提取完整 URL
    .filter(href => href);  // 过滤空链接

  // 2. 转换为 Speculation Rules 支持的 href_matches 格式(通配符匹配)
  // 注:如果是站内链接,也可以提取路径部分(如 href.replace(window.location.origin, \'\'))
  const hrefMatches = asideLinks.map(href => {
    // 对每个链接生成精准匹配的规则(也可根据需求改为通配符,如 `${path}*`)
    return new URL(href).pathname;
  });
const hrefNewMatches = Array.from(new Set(hrefMatches.map(item => JSON.stringify(item)))).map(item => JSON.parse(item));

  // 3. 动态更新 speculationrules 规则
  const rulesScript = document.getElementById(\'speculation-rules\');
  rulesScript.textContent = JSON.stringify({
    "prefetch": [{
      "where": {
        "href_matches": hrefNewMatches // 仅匹配 .aside 内的链接 URL
      },
      "eagerness": "moderate"
    }]
  });
});
</script>

然后又手动补充了一些链接,最终得到

<script id="speculation-rules" type="speculationrules">{"prefetch":[{"where":{"href_matches":["/admin/","/admin/profile.php","/admin/plugins.php","/admin/themes.php","/admin/backup.php","/admin/extending.php","/admin/write-post.php","/admin/write-page.php","/admin/manage-posts.php","/admin/manage-pages.php","/admin/manage-comments.php","/admin/manage-categories.php","/admin/manage-tags.php","/admin/manage-medias.php","/admin/manage-users.php","/admin/options-general.php","/admin/options-discussion.php","/admin/options-reading.php","/admin/options-permalink.php","/admin/options-plugin.php","/admin/theme-editor.php","/admin/options-theme.php","/admin/category.php","/admin/media.php","/admin/user.php"]},"eagerness":"moderate"}]}</script>

这就是typecho默认后台需要加速的链接白名单