Speculation Rules API

Speculation Rules API 是一个由 Google 开发的 JSON 定义的 API,旨在通过推测加载(speculative loading)来提高网页加载性能

  • 以编程的方式进行预加载/预渲染

与旧的 <link rel="prefetch"> (预取的数据存放在 HTTP 缓存)机制不同,通过 Speculation Rules 进行的预取,数据是保存在内存中的,所以浏览器一旦需要可以更快的访问到这些资源。

// eg:
<script type="speculationrules">
  {
    "prefetch": [
      {
        "source": "list",
        "urls": ["list.html", "about.html"]
      }
    ],
    "prerender": [
      {
        "where": { 
          "and": [
            {"href_matches": "/*"},
            {"not": {"href_matches": "/logout"}},
            {"not": {"selector_matches": ".no-prerender"}}
          ]
        }
      }
    ],
    // ...
  }
</script>
// 判断浏览器是否支持 speculationrules
if (HTMLScriptElement.supports?.('speculationrules')) {
  const specScript = document.createElement('script');
  specScript.type = 'speculationrules';
  specRules = {
    prerender: [
      {
        source: 'list',
        urls: ['/xxx.html'],
      },
    ],
  };
  specScript.textContent = JSON.stringify(specRules);
  console.log('添加预渲染规则');
  document.body.append(specScript);
}
posted @ 2024-04-11 16:44  _clai  阅读(19)  评论(0编辑  收藏  举报