Skip to content

Speculation rules: prerendering the next page, and what that page sees before anyone looks

How speculation rules prerender a page in Chrome, when each eagerness level fires, what breaks in a page nobody is looking at yet, and how to test it.

· 7 min read

  • Performance
  • Core Web Vitals
  • JavaScript

A click on a link normally starts a request, a parse and a render, and the user waits for all three. Speculation rules let the page tell the browser which links are likely to be followed next. The browser can then fetch those pages early, or go further and render them in a hidden tab, so the click only has to make an already-finished page visible.

That second mode, prerendering, is the interesting one. It is also the one that breaks things, because the next page runs its JavaScript while nobody is looking at it. This article covers how a prerender works, when Chrome starts one, what the prerendered page can see, and how to test it without fooling yourself.

Every measurement below comes from a small test site served by Node on Linux. The prerender timings come from headless Chrome for Testing 153, launched directly rather than through Playwright, for reasons explained near the end. The eagerness and CSP tests only need prefetch, and ran in Chromium 157 under Playwright. Figures are from single runs.

What a prerender is

The rules are JSON in a script element. This one asks for the pricing page to be prerendered as soon as the current page loads:

<script type="speculationrules">
{
  "prerender": [
    { "urls": ["/pricing"], "eagerness": "immediate" }
  ]
}
</script>

In our test the request for the target page reached the server a few tens of milliseconds after the request for the home page, carrying the header Sec-Purpose: prefetch;prerender. Chrome then built the page in a hidden tab: it parsed the HTML and ran its scripts, and the target page’s own DOMContentLoaded fired about 30 ms into its life. Then it sat and waited.

Two seconds later the home page navigated to it. Instead of fetching, the browser activated the hidden page: it became visible, document.prerendering flipped to false, and a prerenderingchange event fired on the document. The page’s navigation timing entry recorded activationStart at 1,982 ms and first-paint at 2,008 ms. The user saw the page paint 26 ms after the navigation started, with no request on the network.

A prefetch rule does less: the browser downloads the HTML and stops. The navigation still parses and renders, but skips the round trip. Prefetch is cheap and safe for almost any page. Prerender costs memory and CPU for a page that may never be seen, and carries the hazards below.

Document rules and eagerness

A URL list suits a landing page with one obvious next step. Elsewhere, document rules match the links already on the page:

<script type="speculationrules">
{
  "prefetch": [{
    "where": {
      "and": [
        { "href_matches": "/*" },
        { "not": { "href_matches": "/logout" } },
        { "not": { "selector_matches": ".no-prefetch" } }
      ]
    },
    "eagerness": "moderate"
  }],
  "prerender": [{
    "where": { "selector_matches": "main a[href^='/blog/']" },
    "eagerness": "moderate"
  }]
}
</script>

href_matches takes a URL pattern, selector_matches a CSS selector, and and, or and not combine them. The eagerness value decides how much evidence the browser wants before it speculates. We measured each level on desktop with a prefetch rule over two links, from the user action to the request arriving at the server:

Eagerness What triggered the request Delay
immediate Page load none
eager Hovering a link 75 ms
moderate Hovering a link 267 ms
conservative Pressing the pointer down 3 ms

Chrome’s documentation gives a 200 ms hover for moderate and, since Chrome 143, a 10 ms hover for eager on desktop; the rest of each delay is the request reaching our server. conservative waits for pointerdown, which arrives before the click that completes the press, so even that level hides part of the round trip. On a phone there is no hover; Chrome’s documentation says the middle two levels fire about 50 ms after a link enters the viewport. A where rule defaults to conservative and a urls rule to immediate.

Chrome also caps how many prerenders a page can keep alive. In the current source the limit is ten for immediate, after which new ones are refused, and two for every other level, with the oldest dropped when a new one starts; both limits are lowered under memory pressure. So eager on fifty links does not prerender fifty pages. It prerenders the last two hovered.

What the page sees before it is seen

A prerendered page is a real document running real JavaScript, with differences it can detect:

  • document.prerendering is true, and document.visibilityState is hidden.
  • document.hasFocus() is false, and the page has received no input, so anything gated on a user gesture fails or does nothing.
  • sessionStorage is a copy. In our test the home page wrote basket = "1 item", started the prerender, then changed it to "2 items". The prerendered page read "1 item" throughout, and "2 items" the moment it was activated. The swap happens at the prerenderingchange event, so state read from session storage during load can be stale by the time anyone sees it.
  • Performance timing counts from the start of the prerender, not the activation. Our first-paint of 2,008 ms was 26 ms of paint plus 1,982 ms of waiting. Subtract activationStart from any timestamp you report.

Anything that counts a visit must wait, or a page view beacon sent on load counts a page nobody opened:

function onActivated(fn) {
  if (document.prerendering) {
    document.addEventListener("prerenderingchange", fn, { once: true });
  } else {
    fn();
  }
}

onActivated(() => {
  navigator.sendBeacon("/pageview", location.pathname);
  // read sessionStorage here too; it is the live copy now
});

The web-vitals library already does the subtraction: version 6.2.3 reads activationStart and reports FCP, LCP and TTFB relative to activation, so a prerendered page gets the paint times the user saw rather than two-second ones.

The browser also holds back APIs that would be intrusive from a hidden page. The prerendering specification defers getUserMedia, geolocation, Notification.requestPermission, device requests, service worker registration and downloads until activation. Cross-origin iframes do not load until activation either, which keeps most embeds from misfiring, and a prerendered page that navigates to another site is discarded. None of this needs code from you, but it explains why a permission prompt or an embed appears a beat after the page does.

Side effects on the server

Prefetch and prerender both send a GET. If any GET on your site changes state, a request the user never made will change it. The usual offenders are logout links, “mark as read” and “add to basket” links, one-time tokens and rate limiters. Exclude those URLs with a not condition, as in the rules above, and check Sec-Purpose on the server for anything that cannot be excluded: speculative requests carry prefetch or prefetch;prerender, and ordinary navigations carry nothing.

Prerender is same-origin by default. A cross-origin page on the same site has to opt in with the response header Supports-Loading-Mode: credentialed-prerender, and cross-site prerendering is not possible. If your site sends a Content Security Policy, the rules script needs 'inline-speculation-rules', a nonce or a hash in script-src. With script-src 'self' alone, Chrome logged a CSP violation to the console and made no speculative request at all.

Testing it without being misled

Our first harness drove Chromium through Playwright, and prerendering appeared not to work. The request went out with the right header, the click landed, and the new page had an activationStart of zero. The DevTools Protocol’s Preload domain gave the reason: the attempt failed with the status PrerenderingDisabledByDevTools, and the navigation fell back to the prefetched response.

Chromium turns prerendering off when a DevTools client is attached to the page without tab-target support, which is how Playwright attaches. So a browser test of your rules passes, in the sense that the page loads, while never exercising the prerender path. Playwright can still test prefetch and confirm that the rules match the right links. To see a prerender activate, launch Chromium headless with no automation client and have the target page report document.prerendering and activationStart to your own server, which is how the prerender numbers above were collected. In Chrome’s DevTools, the Application panel has a Speculative loads section that lists each candidate URL, its status and why it was or was not triggered.

Where it works

Speculation rules are a Chromium feature today. Prerender has shipped in Chrome and Edge since version 109, with document rules and eagerness since 121. At the time of writing MDN’s compatibility data lists prefetch, not prerender, arriving in Safari 27.3, which is in beta, and prefetch of URL lists only in Firefox Nightly.

That is fine. A browser that does not understand the script type ignores it, so there is no fallback to write. Feature-detect only when generating rules from JavaScript:

if (HTMLScriptElement.supports?.("speculationrules")) {
  const script = document.createElement("script");
  script.type = "speculationrules";
  script.textContent = JSON.stringify({ prerender: [{ urls: [nextUrl] }] });
  document.head.append(script);
}

Astro’s experimental clientPrerender option does exactly this, replacing its usual <link rel="prefetch"> with a speculation rules script carrying both a prerender and a prefetch entry, unless the page already carries document rules.

Start with moderate prefetch across the site, exclude the URLs with side effects, and prerender only the next step you are sure about. Then check your pageview counts and timing data before trusting them. A prerender hides the cost of a navigation rather than removing it, so the page still needs the work in improving INP and stopping font layout shift.

If your site’s navigations feel slow and you want them measured rather than guessed at, see our web development service.

Have something you'd like built?

Tell us what you're building. We'll reply within two working days with questions, an approach and next steps.

Start a project
Esc

↑ ↓ to move · Enter to open