The Speculation Rules API: A Guide to Faster Websites
Published: 2024-05-06 08:58:19

In the pursuit of seamless user experiences, [the Speculation Rules API](https://developer.mozilla.org/en-US/docs/Web/API/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:**

```json
{
    "rules": [
        {   
            "source": "list",
            "urls": [ 
                "/product/12345", 
                "/product/56789" 
            ]
        }
    ]
}
```

**Blog Pagination:**

```json
{
    "rules": [
        {   
            "source": "list",
            "urls": [ "/blog/page/2" ] 
        }
    ]
}
```

**Search Results with “Next page” Link:**

```json
{
  "rules": [
    {
      "prerender": [{
        "urls": ["/list*"],
        "expects_no_vary_search": "params=(\"page\")"
      }]
    }
  ]
} 
```

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

**Injecting rules dynamically:**

```typescript
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);
}
```

**Browser support**

The Speculation Rules API [is currently supported](https://caniuse.com/mdn-html_elements_script_type_speculationrules) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5yyibgzsa7e3n0whupf7.png)

If you need 100% coverage, you can use the old APIs _<link rel=‘prefetch’>_ and _<link rel=‘preload’>_. 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](https://maxfoc.us/) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iabrren2e7953ygdyex3.png)

**Additional resources**

- Documentation from Mozilla https://developer.mozilla.org/en-US/docs/Web/API/Speculation_Rules_API

- API updates in the Google for Developers blog: https://developer.chrome.com/s/results?q=Speculation%20Rules

Thank you for reading!