Web Development

Speculation Rules API: Architecture and Usage Guide

Use the Speculation Rules API to enable near-instant page transitions. Learn to configure prefetching and prerendering rules using JSON for modern MPAs.

390
speculation rules api
Monthly Search Volume

The Speculation Rules API is a web platform feature that allows developers to define which pages the browser should pre-load before a user clicks a link. By downloading or rendering content in the background, this API can provide near-instant page transitions. It is a modern replacement for older resource hints and is designed specifically for multi-page applications (MPAs).

What is the Speculation Rules API?

This API uses a JSON-based structure to give the browser specific instructions on how to handle future navigations. Unlike older methods that target specific resource files, this API targets document URLs. You can implement these rules through a script tag on the page or via an HTTP response header.

The API supports two main actions: * Prefetching: Downloads the HTML of the next page but does not render it or download subresources. This is a lower-cost option. * Prerendering: Downloads the HTML, fetches all subresources, runs JavaScript, and renders the page in a hidden background tab. [A prerender uses roughly the same resources as rendering an iframe] (MDN).

Why Speculation Rules API matters

  • Near-instant navigations. When a page is prerendered, the browser simply swaps the current tab for the hidden one, making the transition feel immediate.
  • Improved Core Web Vitals. Speculative loading can drastically reduce Largest Contentful Paint (LCP) times. [In one scenario, LCP dropped to 50 milliseconds] (Google Codelabs).
  • User-aware resource management. The browser automatically chooses not to speculate if the user is in Battery Saver or Data Saver mode.
  • Dynamic targeting. Unlike static hints, these rules can use CSS selectors to decide which links to load based on how the user interacts with the page.
  • Better cache handling. These rules are more resilient than older hints because they generally do not get blocked by Cache-Control headers. [Chrome caches these prefetched pages for approximately five minutes] (MDN).

How Speculation Rules API works

The API operates by viewing rules defined in a <script type="speculationrules"> element. The browser parses the JSON and adds the instructions to a document-level speculation list.

  1. Rule Definition: You define either a "list" of specific URLs or "document rules" that use conditions to find links on the page.
  2. Condition Matching: For document rules, the browser tests every link on the page against criteria like "href_matches" or "selector_matches."
  3. Speculation Execution: Based on the "eagerness" setting, the browser starts prefetching or prerendering the matched URLs.
  4. Activation: If the user clicks a speculated link, the browser "activates" the pre-loaded content instead of starting a new navigation from scratch.

Variations of eagerness

"Eagerness" dictates when the browser begins the speculative load.

Eagerness Setting Trigger Mechanism Best Use Case
Immediate Happens as soon as the rules are parsed. High-confidence next steps like a "Next" button.
Eager Triggers on slight suggestions of intent (e.g., moving cursor toward a link). High-priority conversion paths.
Moderate Triggers when a user hovers or focuses a link for 200ms. General site navigation for desktop users.
Conservative Triggers on mouse-down or pointer-down events. Low-risk performance boost with minimal waste.

Best practices

  • Start with prefetching. Prefetching is safer for complex sites because it does not execute JavaScript, reducing the risk of unwanted side effects.
  • Exclude sensitive URLs. Always exclude links that perform actions, such as /logout or /add-to-cart, to prevent the browser from accidentally triggering them.
  • Limit your prerenders. Since prerendering uses significant bandwidth and CPU, [Chrome limits the browser to two or ten concurrent prerenders depending on eagerness] (Google Developer).
  • Use progressive enhancement. Feature detect the API using HTMLScriptElement.supports("speculationrules") before applying rules.
  • Monitor for state changes. Use the prerenderingchange event to update content that might have become stale while the page was sitting in a background tab.

Common mistakes

Mistake: Prerendering pages with user-specific state. Fix: Avoid prerendering pages like shopping carts unless you use the Broadcast Channel API to keep the background page synced with the user's current actions.

Mistake: Counting speculative hits as real traffic. Fix: Update your analytics to be "prerender-aware." Ensure your scripts check document.prerendering and wait to log page views until the page is actually activated.

Mistake: Including cross-site links for prerendering. Fix: Be aware that cross-site prerendering is currently not supported. Use prefetching for cross-site links, but only if the user has no cookies set for that destination.

Mistake: Forgetting Content Security Policy (CSP). Fix: If you use CSP, you must explicitly allow 'inline-speculation-rules' in your script-src directive.

Examples

Example: URL List Rule

This rule tells the browser to immediately prerender two specific high-value pages.

<script type="speculationrules">
{
  "prerender": [
    {
      "source": "list",
      "urls": ["/checkout", "/confirmation"]
    }
  ]
}
</script>

Example: Document Rule with Exclusions

This rule prefetches all links on the page except for the logout link and any link with the class .no-speculation.

<script type="speculationrules">
{
  "prefetch": [
    {
      "where": {
        "and": [
          { "href_matches": "/*" },
          { "not": { "href_matches": "/logout" } },
          { "not": { "selector_matches": ".no-speculation" } }
        ]
      },
      "eagerness": "moderate"
    }
  ]
}
</script>

Speculation Rules API vs Resource Hints

Feature Speculation Rules Resource Hints (e.g., link rel=prefetch)
Goal Whole document navigation Individual resource loading
Rendering Supports full prerendering Only supports fetching files
Control Fine-grained (selectors, eagerness) Basic (URL only)
Execution Handles JavaScript on prerender Does not run JavaScript
Risk Higher resource usage Lower resource usage

FAQ

What is the difference between prefetching and prerendering? Prefetching downloads only the HTML document body. It is "lightweight" and does not download images or run scripts. Prerendering loads the entire page, including its subresources and JavaScript, into an invisible tab. Prerendering offers an instant experience but consumes much more memory and data.

How do I know if a page view was prefetched or prerendered? On the server side, look for the Sec-Purpose header. For prefetches, it will say prefetch. For prerenders, it will say prefetch;prerender. On the client side, you can check performance.getEntriesByType("navigation")[0].deliveryType for a value of navigational-prefetch.

Does this work for single-page applications (SPAs)? The API is designed for navigations between different documents (MPAs). It does not apply to internal route changes within a single-page application.

Can I use an external file for rules? Yes. You can use the Speculation-Rules HTTP response header to point to a JSON file. This file must be served with the application/speculationrules+json MIME type.

What happens if a user navigates away before a preloaded page is used? The browser discards the in-memory cache for that speculation when the user navigates to a non-speculated page. If the HTTP headers allow, the resources might still remain in the standard HTTP cache.

Is it possible to cancel a speculation? Yes. You can remove the speculation rules script from the DOM using JavaScript. You can also use the Clear-Site-Data header with the prefetchCache or prerenderCache values to clear existing speculations.

Start Your SEO Research in Seconds

5 free searches/day • No credit card needed • Access all features