Skip to content
jshacks.dev
Browser

The Speculation Rules API: Prefetch and Prerender Pages

How the Speculation Rules API prefetches and prerenders likely next pages with JSON rules: eagerness levels, document rules, safety limits and measuring.

8 min read
Summarize in AI
Flat illustration of a form with one field rejected, with the Google Chrome, Node.js, TypeScript, npm and JavaScript logos.

The fastest page load is the one that has already happened. If a site can guess where the user is going next, such as the next article, the product they are hovering over or the checkout step after the cart, the browser can fetch that page ahead of time, or go further and build it in a hidden tab, so that the click feels instant. For years, this was done with <link rel="prefetch"> and <link rel="prerender">, which were limited and inconsistent, and with libraries that listened for hover events. The Speculation Rules API is the browser's own, richer version: a block of JSON in the page that describes which URLs may be prefetched or prerendered and how eagerly. This post explains how the Speculation Rules API works: the <script type="speculationrules"> format, the difference between prefetch and prerender, URL lists versus document rules with patterns, the eagerness setting, how to add rules from script, what to do about analytics and side effects in prerendered pages, the safety limits the browser applies, how to detect a prerendered page and how to measure the benefit. It is documented on MDN and on web.dev. Support is in Chromium browsers, with other engines at various stages, so treat it as a progressive enhancement: where unsupported, the script block is ignored and nothing breaks.

The format

Rules live in a <script type="speculationrules"> element containing JSON, with prefetch and prerender keys, each holding a list of rule objects.

basic.htmlHTML
<script type="speculationrules">
{
  "prerender": [
    { "source": "list", "urls": ["/pricing", "/signup"] }
  ],
  "prefetch": [
    { "source": "list", "urls": ["/blog/next-post"] }
  ]
}
</script>
Text
(the browser may prerender /pricing and /signup and prefetch /blog/next-post, when it judges it worthwhile)

The rules are hints, not commands: the browser can decide not to speculate because of data saver mode, low memory, battery saver, too many active speculations or user settings, and it will not speculate for a cross-site URL without extra conditions. Your site must work the same whether or not it does.

Prefetch versus prerender

prefetch downloads the main document, the HTML only, and keeps it ready, so that navigation skips the network wait for the first byte. Subresources such as scripts, images and styles are loaded after the click. prerender goes all the way: it loads the page and its subresources in a hidden context, runs its JavaScript and renders it, so on navigation the browser just swaps it in, making the page appear instantly, with the real state, such as scroll and layout, ready.

prefetchprerender
Downloads HTMLYesYes
Downloads subresourcesNoYes
Runs JavaScriptNoYes
Cost if unusedA document downloadA full page load, with CPU and memory
Benefit when usedFaster first byteNear-instant display

Prefetch is cheap and safe for most pages. Prerender costs more, and it executes the page's scripts, which brings in the issues of side effects below. A reasonable default is prefetch for likely links and prerender for the one or two destinations that are very likely.

Eagerness

The eagerness field says how readily the browser should speculate, trading wasted work against speed.

eagerness.htmlHTML
<script type="speculationrules">
{
  "prefetch": [
    {
      "source": "document",
      "where": { "href_matches": "/blog/*" },
      "eagerness": "moderate"
    }
  ]
}
</script>
Text
(links to /blog/ pages are prefetched when the user hovers over them for a short time)

The levels are immediate, which speculates as soon as the rules are seen, eager, a little less aggressive, moderate, which speculates when the user hovers over a link for about 200 milliseconds or on pointer down on some devices, and conservative, which waits for the pointer or touch to press down. For list rules, the default is immediate, and for document rules the default is conservative. Use moderate for general links, since it only spends effort on links that the user shows interest in, and immediate only for a short list of near-certain next pages.

Document rules and patterns

A list of URLs works for a small set of known pages. For a site with many links, document rules look at the links in the page and apply conditions. The where clause can match on href_matches with URL patterns, selector_matches with a CSS selector, and combine them with and, or and not.

document.htmlHTML
<script type="speculationrules">
{
  "prerender": [
    {
      "where": {
        "and": [
          { "href_matches": "/*" },
          { "not": { "href_matches": "/logout" } },
          { "not": { "href_matches": "/cart/add*" } },
          { "not": { "selector_matches": "[rel~=nofollow]" } }
        ]
      },
      "eagerness": "moderate"
    }
  ]
}
</script>
Text
(any same-origin link may be prerendered on hover, except logout, cart-add links and nofollow links)

The exclusions are the important part. Never include URLs that change state on a GET request: logout links, add-to-cart or unsubscribe links, and anything with a side effect. Speculation visits those URLs without a user click, and a prerendered logout could log the user out. The rule of thumb for any link in speculation is that a GET request must be safe and idempotent, which is good practice for HTTP anyway.

Adding rules from script

Rules can be inserted dynamically, which is useful when the likely next page depends on the user's behavior or when a single-page app wants to speculate on its own routes. Create a script element with the right type and put the JSON in textContent.

dynamic.jsJavaScript
function speculate(urls, type = "prefetch") {
  if (!HTMLScriptElement.supports?.("speculationrules")) return false;

  const script = document.createElement("script");
  script.type = "speculationrules";
  script.textContent = JSON.stringify({
    [type]: [{ source: "list", urls }],
  });
  document.head.append(script);
  return true;
}

console.log(speculate(["/checkout"], "prerender"));
Text
true

The static HTMLScriptElement.supports("speculationrules") method tells whether the browser understands the type. Removing the script element cancels the rules, and the browser may drop the speculative pages. A content security policy has to allow it: inline speculation rules need 'inline-speculation-rules' in script-src, or a nonce or hash, since they are a kind of script execution context for policy purposes. The rules can also be delivered by an HTTP header, Speculation-Rules, pointing to a JSON file, which suits CDNs and static hosting.

headers.txtText
Speculation-Rules: "/rules/speculation.json"
Text
(the browser fetches the JSON file, which must be served with Content-Type: application/speculationrules+json)

Prerendered pages run your JavaScript

A prerendered page executes its scripts and loads its subresources before the user has seen it, and that has consequences. Analytics page views would be counted for pages nobody visited. Ads would be requested and impressions recorded. Anything that starts at load, such as a video that autoplays, a notification prompt or a request that marks something as read, would happen early. The platform gives you the tools to handle this: document.prerendering is true while the page is being prerendered, and the prerenderingchange event fires on document when the user navigates to it and it is activated.

prerender.jsJavaScript
function whenVisited(callback) {
  if (document.prerendering) {
    document.addEventListener("prerenderingchange", callback, { once: true });
  } else {
    callback();
  }
}

whenVisited(() => {
  console.log("page is now actually shown");
  sendPageView();
});

function sendPageView() {
  navigator.sendBeacon("/analytics", JSON.stringify({ path: location.pathname }));
}
Text
page is now actually shown

Wrap analytics, ad loading, autoplay and anything with a side effect in whenVisited(). Also note that a prerendered page does not have access to some features until activation: APIs that need user attention, such as notifications permission, geolocation prompts and window.open, are deferred, and cross-origin iframes may wait. Since prerendering uses a separate browsing context, which is why it can be swapped in, sessionStorage is copied, and cookies are shared, so a prerendered page that sets a cookie on load sets it for the real session.

Cross-origin and safety

The browser applies limits. Same-origin prerender is allowed. Same-site cross-origin prerender requires the target to opt in with the Supports-Loading-Mode: credentialed-prerender header. Cross-site prefetch is possible only without the user's credentials and with a referrer policy that does not leak, in a form called anonymous prefetch with "requires": ["anonymous-client-ip-when-cross-origin"] on some browsers. The browser limits the number of concurrent speculations, and a prerender is canceled if the page uses an API that cannot be prerendered, if a redirect leaves the origin or if the memory pressure is high. You do not need to manage that, but you should not rely on a speculation succeeding.

Measuring

Check whether a navigation was served from a prerender: performance.getEntriesByType("navigation")[0].activationStart is greater than zero for a prerendered page, and measure metrics such as Largest Contentful Paint relative to it. Compare real-user timings for navigations that used speculation against those that did not, in your analytics. Chromium's DevTools has a Speculative loads panel in the Application tab, which lists the rules it saw, which URLs were speculated on and why a speculation failed.

measure.jsJavaScript
const [nav] = performance.getEntriesByType("navigation");

if (nav.activationStart > 0) {
  console.log("prerendered, activated after", Math.round(nav.activationStart), "ms");
} else {
  console.log("normal navigation");
}
Text
prerendered, activated after 4210 ms

The value is the time between the start of the prerender and the activation, so the user-perceived load of an activated page is close to zero, and the metrics must be adjusted by subtracting it.

<link rel="prefetch"> fetches a resource at low priority, for a possible future navigation, and is cached in the HTTP cache. It does not render, does not follow document rules and has weaker, inconsistent support for HTML documents. Libraries such as instant.page add a <link rel="prefetch"> or a prefetch on hover, which the speculation rules do natively and with better integration. For a site whose navigations are server-rendered pages, document rules with moderate eagerness are often the single biggest improvement in perceived speed per line of code.

Pitfalls

Including URLs with side effects. Counting analytics views and ad impressions during prerender. Prerendering too many pages, which wastes the user's bandwidth and battery. Ignoring that the browser may refuse, and relying on it for correctness. Blocking the script with a CSP. Serving pages with Cache-Control: no-store or personalized content that is wrong when shown later, since a prerender can be stale by the time the user activates it. And measuring performance without accounting for activationStart.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.