completefrontend
Open lab My progress
THE WEB PERFORMANCE FIELD GUIDE

Speculation Rules

Make the next page appear at once: prefetch or prerender it with speculation rules, pick an eagerness, and keep analytics and side effects safe.

By the end, you can
  • 01
    Prefetch or prerender the next pageWrite list rules and document rules, and know what each action does before the click.
  • 02
    Choose when Chrome startsPick an eagerness, and know Chrome's limits, the HTTP header, and No-Vary-Search.
  • 03
    Keep prerendered pages honestHold back side effects and analytics until the visitor sees the page, and measure what you gained.

The next page, already there

Welcome back to Ravi's mint tea reviews. In lesson 33.1, the Back button became instant. Chrome kept the page Asha left, and showed it again. This lesson goes the other way. It makes the next page appear at once.

Asha is reading the reviews. She taps Mint tea in the shop. For almost half a second, nothing changes. Then the Mint tea page appears. Ravi adds a few lines to his page, and she tries again. This time the Mint tea page is there 42 ms after her tap.

How can a page appear sooner than the server can even answer? Here is what Chrome showed, in real frames:

Asha taps Mint tea in the shop twice, in real frames from Chrome. Top, with no rules: the reviews are on screen at the tap, and the Mint tea page appears 475.9 ms later. Bottom, with Ravi's prerender rule: the Mint tea page appears 42 ms after the tap. Beside each pair, a bar drawn to scale from the tap to the page on screen.No rulesThe reviews page at the tap: Mint tea reviews, with the link Mint tea in the shop near the top.475.9 ms after the tap: the Mint tea page, with Ben's photo of the tea, its price and Add to cart.at the tap475.9 ms later475.9 msPrerenderedThe reviews page at the tap: Mint tea reviews, with the link Mint tea in the shop near the top.42 ms after the tap: the Mint tea page, with Ben's photo of the tea, its price and Add to cart.at the tap42 ms later42 msfrom the tap to the page on screen, to scale
Real frames from Chrome, the middle of 5 taps each. Without rules, the reviews stayed on screen for 475.9 ms. Prerendered, the Mint tea page was there 42 ms after the tap.

Here are the two times as code:

Asha's two tapsPop out in the code editor (opens in a new tab)JavaScript
// Asha taps "Mint tea in the shop". When was the Mint tea page on screen?// In ms after her tap: the middle of 5 tries, from Chrome's own screenshots.const noRules = 475.9;const prerendered = 42; console.log(`No rules: on screen in ${noRules} ms.`);console.log(`Prerendered: on screen in ${prerendered} ms.`);
  • Lines 1 and 2 are comments. A millisecond (ms) is a thousandth of a second. The course tapped with a mouse click, 5 times for each version. It used Chrome 157, in a window 500 pixels wide, with the CPU 4 times slower.
  • The course's server played the part of DevTools' Fast 4G for every request. Each answer waited 165 ms, then came at Fast 4G's speed.
  • Line 3 is the tap with no rules: 475.9 ms until the Mint tea page was on screen.
  • Line 4 is the tap with Ravi's new lines: 42 ms.
  • Lines 6 and 7 print No rules: on screen in 475.9 ms. and Prerendered: on screen in 42 ms.

Here's the answer. The second time, Chrome didn't load the Mint tea page after the tap at all. It had loaded it seconds earlier, out of sight, while Asha read. The tap only showed it.

Ravi asked Chrome to do that with speculation rules. A speculation is a guess. Speculation rules are a site's guesses about the page a visitor will open next. They're written in JSON, the plain-text format JavaScript objects are written in.

Real-life analogyA barista who knows your usual

Every morning you order a mint tea at the same café. One day the barista sees you at the door. She gets a cup and the mint leaves ready. The next day she brews the whole tea before you reach the counter. When you order, it's already there. If you order a coffee, her work was for nothing.

In real life: The barista's guess
In JavaScript: Speculation rules: the page Ravi thinks Asha will open next
In real life: Getting the cup and the leaves ready
In JavaScript: Prefetch: Chrome fetches the next page's HTML early
In real life: Brewing the whole tea
In JavaScript: Prerender: Chrome loads the whole page, out of sight
In real life: You order
In JavaScript: Asha taps the link
In real life: You order a coffee instead
In JavaScript: A guess nobody uses: the work is wasted
The main idea

Speculation rules list the pages a visitor will probably open next. The browser fetches them, or loads them completely out of sight, before the click. When the visitor clicks, the page is already there. A wrong guess costs the visitor data and battery, so guess with care.

The rest of this lesson goes step by step. First, the two things a rule can ask for, and the two kinds of rule. Then when Chrome starts, and where rules can live. Then the side effects: a page that runs while nobody looks, and analytics that count a visit that never happened. Last, how to measure what you gained.

Prefetch or prerender

Here is Ravi's rule. It sits at the end of the reviews page:

Ravi's first ruleHTML
<script type="speculationrules">{  "prerender": [    { "urls": ["/shop/mint-tea"] }  ]}</script>
  • Line 1 opens a script tag of the type speculationrules. Its content is JSON, not JavaScript. The browser reads it as rules and runs nothing.
  • Line 3 names the action: what to do with the page. Here it's prerender.
  • Line 4 is a rule. Its urls list says which addresses to prerender. There is one: the Mint tea page.

Change line 3 to prefetch, and you have the other action. The two words ask for very different amounts of work:

  • Prefetch fetches the next page's HTML and keeps it in memory. Nothing else happens until the click.
  • Prerender loads the whole page in a hidden tab: its HTML, CSS and images. Its scripts run too. Chrome's docs say a prerender "behaves as if the page has been opened in an invisible background tab".

Lesson 16.4 met <link rel="prefetch">. It put a file in the HTTP cache. A speculation rules prefetch is different. It keeps a whole page, ready for the navigation, even one the HTTP cache wouldn't keep.

The course tapped the link 5 times with each version:

Three versions, one tap eachPop out in the code editor (opens in a new tab)JavaScript
// 5 taps for each version. The middle tap of each, in ms.// onScreen: from the tap to the Mint tea page on screen.// lcp: the page's own LCP, counted from when Asha opened it.const taps = [  { rules: "none", onScreen: 475.9, lcp: 460 },  { rules: "prefetch", onScreen: 58.2, lcp: 44 },  { rules: "prerender", onScreen: 42, lcp: 31 },];for (const tap of taps) console.log(`${tap.rules}: on screen in ${tap.onScreen} ms, LCP ${tap.lcp} ms`);
  • Lines 1 to 3 are comments.
  • Lines 5 to 7 hold one version each: no rules, Ravi's rule with prefetch, and with prerender.
  • lcp is the page's Largest Contentful Paint (lesson 17.1): when its biggest picture or text appeared. For a prerendered page, it counts from when Asha opened it.
  • Line 9 prints none: on screen in 475.9 ms, LCP 460 ms first.
  • Then it prints prefetch: on screen in 58.2 ms, LCP 44 ms and prerender: on screen in 42 ms, LCP 31 ms.
Three taps on Mint tea in the shop, to scale, from the tap to the page on screen. No rules: waiting 418.2 ms for the HTML, then on screen at 475.9 ms. Prefetch: waiting 2.7 ms for the HTML, then on screen at 58.2 ms. Prerender: on screen at 42 ms.the tapNo rules475.9 msPrefetch58.2 msPrerender42 mswaiting for the HTMLChrome's own work
The opening picture's two taps and the prefetched tap, to scale. Shaded: waiting for the HTML. Plain: Chrome reading, drawing and showing the page. The prerendered page had done its waiting before the tap.

Without rules, the tap started everything. Chrome asked Ravi's server for the page, then waited. The first byte came 418.2 ms after the load began. Most of that was waiting: 165 ms on the network, and 250 ms while Ravi's server built the page.

The prefetch removed that wait. The prerender removed nearly all the rest, because the page had loaded before the tap. The Mint tea page's own navigation entry, from lesson 5.1, shows both:

What the Mint tea page wrote downPop out in the code editor (opens in a new tab)JavaScript
// The Mint tea page's navigation entry, from the taps in the picture.// In ms, counted from when Chrome started loading the page.const prefetched = { responseStart: 2.7, activationStart: 0 };const prerendered = { loadEventEnd: 444.7, activationStart: 3596.7 }; console.log(`Prefetched: the first byte came ${prefetched.responseStart} ms in.`);console.log(`Prerendered: loaded at ${prerendered.loadEventEnd} ms, opened at ${prerendered.activationStart} ms.`);
  • Line 3 is the prefetched page. Its first byte came 2.7 ms in, from memory. Its deliveryType said navigational-prefetch.
  • Line 4 is the prerendered page. Its load event ended at 444.7 ms. But Asha only opened it at 3,596.7 ms. That moment is called activationStart.
  • Lines 6 and 7 print Prefetched: the first byte came 2.7 ms in. and Prerendered: loaded at 444.7 ms, opened at 3596.7 ms.

Why it matters: on Ravi's small page, the slow part was the server. So a prefetch already won most of the time back. A page that does more of its own work after the HTML arrives gains more from a prerender, which does that work before the tap. But a prerender also costs more: memory, CPU and data, for a page Asha may never open.

Pick a version to see what Chrome reported for its tap:

Playground: three taps
The rule on the reviews pageJSON
{
  "prerender": [
    { "urls": ["/shop/mint-tea"] }
  ]
}
PrerenderRecorded
On screen after the tap42 ms
LCP, from the opening31 ms
responseStart416 ms
activationStart3,596.7 ms
deliveryTypenavigational-prefetch
Sec-Purpose headerprefetch;prerender
Chrome's status, in orderprefetch: Running (PrefetchNotFinishedInTime), Success (PrefetchResponseUsed); prerender: Pending, Running, Ready
Try it yourself
Prerender

Chrome loaded the whole page in a hidden tab, seconds before the tap. The tap only showed it.

Recorded in Chrome 157, with a CPU 4 times slower and a server that played Fast 4G. 5 taps each: the two times are the middle tap's; the rest come from the tap in the opening picture.

List rules and document rules

Ravi's rule names one address. That's a list rule: you list the URLs, like a shopping list. The other kind is a document rule. It describes which of the page's links to pick, like "anything from the tea shelf". Chrome then looks through the links itself.

Ravi's page has three links: Mint tea in the shop, Sign out, and Back to the top. He tries a document rule that picks every link on his site:

A rule for every linkJSON
{  "prerender": [{    "where": { "href_matches": "/*" },    "eagerness": "immediate"  }]}
  • Line 3 holds where. That makes it a document rule. Every link is tested against the condition inside.
  • href_matches tests a link's address against a URL pattern: an address with wildcards. A * matches anything, so /* matches every page on Ravi's site.
  • Line 4 sets the eagerness to immediate: start at once. The next section explains eagerness.

Chrome skips links to a spot on the same page, like Back to the top. That left two links. The course loaded the page and waited 5 seconds. Asha touched nothing:

Two rules, and Asha's sessionPop out in the code editor (opens in a new tab)JavaScript
// Ravi's page with each rule, for 5 seconds. Asha never touched a link.const everyLink = { speculated: ["/shop/mint-tea", "/account/sign-out"], signedIn: false };const notAccount = { speculated: ["/shop/mint-tea"], signedIn: true }; for (const [rule, result] of Object.entries({ everyLink, notAccount }))  console.log(`${rule}: ${result.speculated.join(" and ")}. Signed in: ${result.signedIn}`);
  • Line 2 is the rule above. Chrome speculated on both links, and Asha was no longer signed in.
  • Line 3 is the second rule, below. It picked only the Mint tea page.
  • Lines 5 and 6 print everyLink: /shop/mint-tea and /account/sign-out. Signed in: false and notAccount: /shop/mint-tea. Signed in: true.

With the first rule, Chrome prerendered the sign-out page. Its first step, fetching the page, reached Ravi's server. The server did what a sign-out page does: it cleared Asha's session cookie. Nobody clicked anything, and Asha was signed out. The HTML standard warns about this very case, with a link to /logout.

Ravi's three links, and what each document rule did with them. With every link on the site: Mint tea in the shop was prerendered, Sign out was prerendered and signed Asha out, and Back to the top was skipped. With every link except /account/: Mint tea in the shop was prerendered, Sign out was left out, and Back to the top was skipped.reviewsMint tea in the shopSign outBack to the topevery link: /*/*, not /account/*prerenderedprerenderedsigned Asha outleft outskippedskipped
What each rule did in the recording, while Asha touched nothing. Chrome skips a link to a spot on the same page. Only the second rule kept Asha signed in.

The fix is a better condition:

Every link, except the account pagesJSON
{  "prerender": [{    "where": {      "and": [        { "href_matches": "/*" },        { "not": { "href_matches": "/account/*" } }      ]    },    "eagerness": "immediate"  }]}
  • Line 4 opens and: a link must match every condition inside it.
  • Line 5 is the same /* as before.
  • Line 6 uses not, which turns a condition around. A link matches only if its address isn't under /account/.

A condition can also test the link element itself, with selector_matches and a CSS selector, like .no-prerender. Ravi could put that class on any link he never wants speculated.

Why it matters: a link that changes something when it's fetched must never be speculated. Think of sign out, add to cart, or delete. Leave them out of your rules.

When Chrome starts: eagerness

A document rule can pick dozens of links. Prerendering all of them at once would waste a lot. So each rule has an eagerness: how sure Chrome should be before it starts.

Real-life analogyA waiter reading the signs

A good waiter watches the table. Some guests always have the soup, so he brings it as they sit down. For others, he waits for a glance at the soup on the menu. Or for a long look. A careful waiter waits until the guest starts to say "soup".

In real life: Bringing the soup as you sit down
In JavaScript: immediate: as soon as Chrome reads the rule
In real life: Waiting for a glance at the soup
In JavaScript: eager: a pointer resting on the link for 10 ms
In real life: Waiting for a long look
In JavaScript: moderate: a pointer resting on the link for 200 ms
In real life: Waiting until you start to say "soup"
In JavaScript: conservative: a press on the link

Here are the four levels, from Chrome's docs and its source code:

  • immediate: as soon as Chrome reads the rule. It's the default for list rules.
  • eager: on a computer, when a pointer rests on the link for 10 ms. On a phone, when the link has been on screen for 50 ms.
  • moderate: on a computer, when a pointer rests on the link for 200 ms, or on a press if that comes first. On a phone, Chrome guesses from scrolling. It picks a big link near your last touch, 500 ms after you stop scrolling.
  • conservative: when a pointer or a finger presses the link. It's the default for document rules.

The course tested moderate with a mouse, which a phone doesn't have. Ravi's rule picked every /shop/ link:

A moderate rule for shop linksJSON
{  "prerender": [{    "where": { "href_matches": "/shop/*" },    "eagerness": "moderate"  }]}

Line 3 picks every link whose address starts with /shop/. Line 4 sets the eagerness. Then the course rested the pointer on Mint tea in the shop for a while, and moved it away:

How long the pointer restedPop out in the code editor (opens in a new tab)JavaScript
// The pointer rests on "Mint tea in the shop", then moves away. The rule is moderate.// restedFor: how long it rested, in ms. askedAt: when Chrome asked for the page, in ms.const hovers = [  { restedFor: 129, askedAt: null },  { restedFor: 166, askedAt: null },  { restedFor: 271, askedAt: 213.9 },  { restedFor: 414, askedAt: 212.3 },];for (const hover of hovers) console.log(`${hover.restedFor} ms: ${hover.askedAt ? `asked at ${hover.askedAt} ms` : "nothing"}`);
  • Lines 4 and 5 are rests of 129 ms and 166 ms. Chrome asked for nothing.
  • Lines 6 and 7 are rests of 271 ms and 414 ms. Chrome asked for the page 213.9 ms and 212.3 ms after the pointer arrived.
  • Line 9 prints 129 ms: nothing, 166 ms: nothing, 271 ms: asked at 213.9 ms and 414 ms: asked at 212.3 ms.
On a computer, how long the pointer rests on a link before Chrome speculates, to scale from the moment it arrives. Immediate: already started when the page loaded. Eager: a 10 ms rest. Moderate: a 200 ms rest; in the recording, Chrome asked for the page at 213.9 ms. Conservative: nothing until the button goes down, here at 408.5 ms.the pointer arrivesimmediatestarted when the page loaded, before the pointer movedeagera 10 ms restmoderatea 200 ms rest; asked at 213.9 msconservativeuntil the press, at 408.5 ms
How long each eagerness waits on a computer, to scale. Shaded: the rest Chrome waits for, 10 ms for eager and 200 ms for moderate, in its code. In the recording, moderate asked for the page at 213.9 ms. Plain: the time until the button went down.

So the 200 ms wait is real. A pointer that only passes over a link costs nothing. One that stops on it starts a prerender.

Conservative starts later, at the press. In the course's test, Chrome asked for the page 6.1 ms after the button went down. The click came 108.3 ms after the prerender started, long before the server answered. Chrome showed the prerender anyway, and let it finish loading in view. LCP was 375.7 ms after the click, not 460.

Try each test the course ran:

Playground: the pointer on the link
The rule on the reviews pageJSON
{
  "prerender": [{
    "where": { "href_matches": "/shop/*" },
    "eagerness": "moderate"
  }]
}
moderateRecorded
Try 1: rested271 ms
Try 1: Chrome asked at213.9 ms
Try 2: rested270 ms
Try 2: Chrome asked at219.3 ms
Try it yourself
moderate, rest 250 ms

Chrome asked for the page while the pointer rested on the link, in all 2 tries.

Recorded in Chrome 157 with a mouse, 2 tries each. Times are in ms after the pointer moved onto Mint tea in the shop. Rests come from the page's own pointer events, or last until the press.

Chrome also limits how many speculations it keeps at once. Read the table across: each row is an eagerness, with Chrome 157's limits on a computer.

How many speculations Chrome keeps at once
EagernessPrefetchesPrerendersWhen the limit is reached
immediate50 at most.10 at most.New ones don't start while the limit is reached.
eager2 at most.2 at most.The oldest one is canceled to make room.
moderate2 at most.2 at most.The oldest one is canceled to make room.
conservative2 at most.2 at most.The oldest one is canceled to make room.

Chrome's docs give phones room for 6 eager or moderate prefetches. And sometimes Chrome won't speculate at all:

  • when the visitor has turned on Save-Data;
  • when Energy saver is on and the battery is low;
  • when the device is short of memory;
  • when the Preload pages setting is off, as some ad-blocking extensions leave it;
  • when the page is in a background tab.

Why it matters: speculation is a hint, not an order. Pick the eagerness that matches how sure you are, and make sure the page works the same when Chrome ignores the hint.

Writing prerender-safe pages

A prerendered page isn't a picture of a page. It's the real page, running. Here is what the Mint tea page saw, in the opening's prerendered tap:

The Mint tea page, before Asha's tapPop out in the code editor (opens in a new tab)JavaScript
// What the prerendered Mint tea page saw, in ms from the start of its own load.const page = { prerendering: true, visibility: "hidden", loadEventEnd: 444.7, prerenderingchange: 3602.6 }; console.log(`Started with prerendering ${page.prerendering}, ${page.visibility}.`);console.log(`Loaded at ${page.loadEventEnd} ms. Shown at ${page.prerenderingchange} ms.`);
  • Line 2 holds what it noted. It started with document.prerendering true, and hidden. Its load event ended at 444.7 ms. It was shown at 3,602.6 ms.
  • Lines 4 and 5 print Started with prerendering true, hidden. and Loaded at 444.7 ms. Shown at 3602.6 ms.

document.prerendering is true while a page prerenders. When the visitor opens it, the browser activates the page. The prerenderingchange event fires on the document, and document.prerendering turns false. It never turns true again.

Real-life analogyA dress rehearsal

Before opening night, the cast plays the whole show in an empty theatre. Lights, music, costumes: everything runs. But nobody sells tickets, and nobody counts the audience. Those wait for the real show.

In real life: The whole show, in an empty theatre
In JavaScript: The prerendered page, loading and running hidden
In real life: Lights, music and costumes
In JavaScript: HTML, CSS, images and scripts
In real life: Selling tickets and counting the audience
In JavaScript: Side effects: page views, changes on the server
In real life: Opening night
In JavaScript: Activation: prerenderingchange

The browser holds some things back by itself. The Prerendering Revamped spec lists them:

  • Dialogs such as alert() don't show, and print() does nothing.
  • Downloads wait for activation.
  • Many APIs that ask the visitor for permission, such as geolocation and notifications, wait for activation.
  • Anything that needs a tap or a key press first, such as opening a pop-up, fails. A prerendered page has had none.

Scripts still run, and so do fetch() and navigator.sendBeacon(). A side effect is anything a page does that changes the world outside it: a change on the server, a counted view, an ad marked as seen. Holding those back is your job.

Your server can tell a speculative request apart. Every request a prerender makes carries one more header:

A request made ahead of timeHTTP
GET /shop/mint-tea HTTP/1.1Sec-Purpose: prefetch;prerender

Line 2 is Sec-Purpose. A prerender sends prefetch;prerender. A prefetch sends just prefetch. The course's server saw both. A server can use it to say no:

No sign-out ahead of timeJavaScript
// Ravi's server: never sign anyone out on a request made ahead of time.if (url.pathname === "/account/sign-out" && request.headers["sec-purpose"]) {  response.writeHead(503).end();  return;}
  • Line 2 spots a sign-out request with a Sec-Purpose header.
  • Line 3 answers 503 and changes nothing. Chrome's docs say an answer outside 200 to 299 stops a prerender, and a prefetch is thrown away.

Why it matters: whatever your page does on load, a prerender does too, for a visitor who may never come. Inside the page, wait for activation before any side effect. The next section shows how.

Analytics and prerendering

Analytics count page views. Ravi's script on the Mint tea page counted a view as the page loaded:

Ravi's analytics, as it wasJavaScript
// Ravi's analytics: count a page view as the page loads.navigator.sendBeacon("/visit", location.pathname);

Line 2 sends a small report to /visit with navigator.sendBeacon(), as in lesson 12.3. The reviews page had the prerender rule. Asha read the reviews and never opened the Mint tea page:

Views of a page nobody openedPop out in the code editor (opens in a new tab)JavaScript
// Page views Ravi's server counted while Asha read the reviews.// She never opened the Mint tea page. 2 visits for each version.const countsAtLoad = [1, 1];const countsWhenShown = [0, 0]; console.log(`Counts at load: ${countsAtLoad.join(" and ")} views`);console.log(`Counts when shown: ${countsWhenShown.join(" and ")} views`);
  • Line 3 is the script above: 1 view, in both visits.
  • Line 4 is the fixed script, below: 0 views.
  • Lines 6 and 7 print Counts at load: 1 and 1 views and Counts when shown: 0 and 0 views.

The view came from the hidden page, about 440 ms after Chrome asked for it. Its request carried Sec-Purpose: prefetch;prerender. Ravi's server counted a visit that never happened. Here is the fix:

Ravi's analytics, prerender-safeJavaScript
// Ravi's analytics: count a page view once Asha sees the page.function countView() {  navigator.sendBeacon("/visit", location.pathname);} if (document.prerendering) {  document.addEventListener("prerenderingchange", countView, { once: true });} else {  countView();}
  • Lines 2 to 4 put the report in a function, so it can wait.
  • Line 6 checks document.prerendering. If the page is still hidden, line 7 calls the function on prerenderingchange, once.
  • Lines 8 to 10 count the view straight away on a normal visit.

When Asha did open the page, each script sent one view. The old one sent it about 2.7 seconds before her tap, from the hidden page. The fixed one sent it 5.5 ms after the tap.

Playground: page views
Ravi's analytics on the Mint tea pageJavaScript
// Ravi's analytics: count a page view as the page loads.
navigator.sendBeacon("/visit", location.pathname);
Asha never opens itRecorded
Visit 1: views1
Visit 1: the viewsent from the hidden page, Sec-Purpose: prefetch;prerender
Visit 2: views1
Visit 2: the viewsent from the hidden page, Sec-Purpose: prefetch;prerender
Try it yourself
2 page views in 2 visits

Asha never opened the Mint tea page, but Ravi's server counted a view in each visit.

Recorded in Chrome 157: the reviews page prerendered the Mint tea page, and Ravi's server counted every report to /visit.

Chrome's docs say Google Analytics already waits for activation. Check your own tools.

Why it matters: without the fix, every prerender Asha never opens looks like a visit, and your page views go up for no reason.

Measuring the gain

Speculation is a guess, so check that it pays. You need two things: which visits it sped up, and how fast they were. Tag each visit:

Which kind of visit was this?JavaScript
// Which kind of visit was this? Send it with the page's LCP.const [visit] = performance.getEntriesByType("navigation");let kind = "normal";if (document.prerendering || visit.activationStart > 0) kind = "prerendered";else if (visit.deliveryType === "navigational-prefetch") kind = "prefetched";console.log(kind);
  • Line 2 gets the page's navigation entry.
  • Line 4: the page was prerendered if it still is, or if its activationStart is above 0.
  • Line 5: deliveryType is navigational-prefetch when the page came from a prefetch.
  • Line 6 prints the kind.

Send the kind with each LCP report. From Ravi's taps, that would show 460 ms for normal visits, 44 ms prefetched and 31 ms prerendered. The web-vitals library already counts a prerendered page's LCP from activationStart, as Chrome's field data does. Field data is what real visitors' browsers report.

Also count the guesses that missed. Chrome's docs suggest an event each time you add rules, compared with the prerendered visits. If only a few of your prerenders are ever opened, you speculate too much.

On your own computer, Chrome's DevTools shows every guess. Open the Application panel, and find Speculative loads under Background services. The Rules tab lists each rule set. The Speculations tab lists every URL, with its action and its status. Reload the page after opening the panel, or it stays empty.

Was this very page prefetched or prerendered? The lab reads its navigation entry:

Playground: was this page prerendered?
What this lab readsJavaScript
// What this lab reads, on this page.
const supported = HTMLScriptElement.supports?.("speculationrules");
const [visit] = performance.getEntriesByType("navigation");
const prerendered = document.prerendering || visit.activationStart > 0;
const prefetched = visit.deliveryType === "navigational-prefetch";
This pagereading
Speculation rules supported…
document.prerendering…
activationStart…
deliveryType…
Try it yourself
Your browser

Reading this page's navigation entry.

This reads your own browser, on this page. Browsers without these APIs say so instead of guessing.

Lines 2 to 5 of the lab's code check support, then read activationStart and deliveryType. Chrome can also prerender a page you type in the address bar, so even this page might say prerendered.

Why it matters: a guess you don't measure may cost your visitors data for nothing, or win them time you never hear about.

Now, or when Asha sees it?

Each job below runs on Ravi's Mint tea page. Sort it by when it should run, if the page might be prerendered:

Now, or when Asha sees it?
  • Draw the price and the photo
  • Load the page's CSS and fonts
  • Fetch the tea's details from Ravi's API
  • Send a page view to analytics
  • Add the tea to her recently viewed list on the server
  • Count an ad as seen
  • Start a video with sound
  • Show 'Signed in as Asha' from a cookie
Try it yourself
0 of 8 correct

Sort each job by when it should run on a page that may be prerendered.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common mix-ups

  • "Prefetch and prerender do the same thing." No. A prefetch keeps the HTML. A prerender loads and runs the whole page, hidden.
  • "A speculation rules prefetch is the same as link rel=prefetch." No. The link puts a file in the HTTP cache. The rule keeps a whole page for the navigation, even one the HTTP cache wouldn't keep.
  • "Moderate starts as soon as the pointer touches a link." No. On a computer, the pointer must rest for 200 ms. Rests of 129 ms and 166 ms started nothing.
  • "A prerendered page waits to run its scripts until it's shown." No. Ravi's analytics ran in the hidden page, and the server counted a view.
  • "No-Vary-Search alone stops duplicate prerenders." No. Chrome can't read a header before the response. The hint in the rule does it.
  • "If a browser supports speculation rules, it always speculates." No. Save-Data, Energy saver, low memory, a setting or a background tab can stop it.

Practice exercises

Answer first, then use the hints.

Exercise 1 · Warm-upThe time a prerender saved

What does this print?

Starter codePop out in the code editor (opens in a new tab)JavaScript
const noRules = 475.9;
const prerendered = 42;
console.log(`Prerendering saved ${(noRules - prerendered).toFixed(1)} ms.`);

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upA list rule's start

    Ravi's list rule has no eagerness key. When does Chrome start speculating on its URL?

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeThe eager pointer

      In the hover playground, pick the eager test. In its first try, how many ms after the pointer arrived did Chrome ask for the Mint tea page?

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeA header Chrome can't read

        Ravi's CDN sends this header, but nothing is speculated. What's missing?

        Starter codeHTTP
        Speculation-Rules: /rules/shop.json

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeRavi's page in DevTools

          Open this copy of Ravi's page in Chrome. Its rule prerenders product.html. Open DevTools and find the speculation. What status does it show?

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeRecently viewed, safely

            Ravi's Mint tea page adds the tea to Asha's recently viewed list. Make it wait until she sees the page. Which event do you use?

            Starter codeJavaScript
            // Ravi's "recently viewed" list: his server adds the tea when this runs.
            fetch("/recently-viewed", { method: "POST", body: "mint-tea" });

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask what Chrome does before the tap, and what waits for the visitor.

              The speculation rules quiz · 7 questionsScore: first tries count
              1. Question 1 of 7What does the first line of the opening example print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                // Asha taps "Mint tea in the shop". When was the Mint tea page on screen?
                // In ms after her tap: the middle of 5 tries, from Chrome's own screenshots.
                const noRules = 475.9;
                const prerendered = 42;
                
                console.log(`No rules: on screen in ${noRules} ms.`);
                console.log(`Prerendered: on screen in ${prerendered} ms.`);

                Choose an answer to see the explanation.

              2. Question 2 of 7A document rule has no eagerness key. When does Chrome speculate on its links?

                Choose an answer to see the explanation.

              3. Question 3 of 7What does a prerender do that a prefetch doesn't?

                Choose an answer to see the explanation.

              4. Question 4 of 7On a computer, a moderate rule picks a link. The pointer rests on it for 150 ms, then moves on. What does Chrome do?

                Choose an answer to see the explanation.

              5. Question 5 of 7A rule file is sent with Content-Type: application/json. What happens?

                Choose an answer to see the explanation.

              6. Question 6 of 7Why add expects_no_vary_search to a document rule?

                Choose an answer to see the explanation.

              7. Question 7 of 7A prerendered page sends its page view as it loads. The visitor never opens it. What does the server see?

                Choose an answer to see the explanation.

              Key takeaways

              • Speculation rules are JSON guesses about the next page. A prefetch keeps its HTML. A prerender loads and runs it, hidden.
              • List rules name URLs. Document rules pick links with where. Leave out any link that changes something when it's fetched.
              • Eagerness says when to start: immediate, eager (a 10 ms rest), moderate (200 ms) or conservative (a press). Chrome keeps 2 of each, except immediate.
              • The Speculation-Rules header points at a rule file: quote the URL, and serve it as application/speculationrules+json.
              • No-Vary-Search lets one prerender serve other query strings. expects_no_vary_search stops duplicates.
              • Hold side effects and analytics until prerenderingchange. Measure with activationStart and deliveryType.

              Remember the one-liner.
              Guess the next page in JSON, let the browser get it ready, and save every side effect for the moment the visitor arrives.

              Sources

              The facts on this page come from these specs, docs and source files:

              Coming next: Prefetching strategies. You've seen how to speculate. Next, you'll see how to choose which pages to guess, and what wrong guesses cost your visitors.

              CompleteFrontend Clear concepts. Working examples.