The Speculation Rules API: A Guide to Faster Websites

qostya

Constantine

Posted on May 6, 2024

The Speculation Rules API: A Guide to Faster Websites

In the pursuit of seamless user experiences, the Speculation Rules API offers web developers a powerful tool to combat the latency that often accompanies web page navigation. By instructing the browser about likely user actions, this API enables proactive resource prefetching and even full-page prerendering, leading to significantly faster-perceived load times.

Understanding the Speculation Rules API

The core principle of the Speculation Rules API is providing predictive hints to the browser. Developers have the flexibility to indicate potential page navigations, empowering the browser to anticipate user behaviour and optimize resource loading ahead of time.

Prefetching vs. Prerendering

  • Prefetching: The browser downloads a target document and its associated resources (images, scripts, etc.) and stores them in its cache for later use. This ensures immediate availability if the user navigates to that page.

  • Prerendering: This takes preloading further by instructing the browser to render the entire document (including JavaScript execution) in a hidden state. The user clicks the link, the prerendered page is displayed almost instantaneously.

Speculation Rules in Practice: Code Examples

Speculation Rules are expressed in JSON format and can be embedded either inline in the HTML or served as a separate file:

E-commerce Product Listings:

{
    "rules": [
        {   
            "source": "list",
            "urls": [ 
                "/product/12345", 
                "/product/56789" 
            ]
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Blog Pagination:

{
    "rules": [
        {   
            "source": "list",
            "urls": [ "/blog/page/2" ] 
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Search Results with “Next page” Link:

{
  "rules": [
    {
      "prerender": [{
        "urls": ["/list*"],
        "expects_no_vary_search": "params=(\"page\")"
      }]
    }
  ]
} 
Enter fullscreen mode Exit fullscreen mode

Example: <a href="/list?page=2">Next page</a>

Injecting rules dynamically:

function preloadPages(urls: string[], specType: 'prefetch' | 'prerender' = 'prefetch') {
  if (!HTMLScriptElement.supports?.HTMLScriptElement.supports("speculationrules") {
    return;
  }

  const specScript = document.createElement("script");
  const specRules = {
    [specType]: [{ "source": "list", urls }],
  };

  specScript.type = "speculationrules";
  specScript.textContent = JSON.stringify(specRules);

  document.body.append(specScript);
}
Enter fullscreen mode Exit fullscreen mode

Browser support

The Speculation Rules API is currently supported in Chromium-based browsers (like Chrome, Edge, and Opera), which cover approximately 70% of the global browser market. While it doesn’t yet function in Firefox or Safari, it won’t break anything if you start using it today. Users on other platforms will gradually experience its benefits as browser support expands.

Speculation API browser support

If you need 100% coverage, you can use the old APIs and . More information from Addy Osmani: https://medium.com/reloading/preload-prefetch-and-priorities-in-chrome-776165961bbf.

How we use it in our extension

We use the Speculation Rules API in the MaxFocus: Link Preview extension to improve preview loading speeds. When a user’s behaviour indicates they prefer the “Open on a long click” method, we dynamically inject Speculation Rules with the “prefetch” directive on the ‘mouse down’ event. This tells the browser to start preloading the linked page’s resources in the background, ensuring a near-instant preview experience when the user finally long-clicks to open it.

MaxFocus: Link preview extension

Additional resources

Thank you for reading!

💖 💪 🙅 🚩
qostya
Constantine

Posted on May 6, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related