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.
- 01Prefetch or prerender the next pageWrite list rules and document rules, and know what each action does before the click.
- 02Choose when Chrome startsPick an eagerness, and know Chrome's limits, the HTTP header, and No-Vary-Search.
- 03Keep 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:
Here are the two times as code:
// 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.andPrerendered: 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.
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
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:
<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
urlslist 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:
// 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 withprerender. lcpis 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 msfirst. - Then it prints
prefetch: on screen in 58.2 ms, LCP 44 msandprerender: on screen in 42 ms, LCP 31 ms.
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:
// 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
deliveryTypesaidnavigational-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.andPrerendered: 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:
{
"prerender": [
{ "urls": ["/shop/mint-tea"] }
]
}42 ms31 ms416 ms3,596.7 msnavigational-prefetchprefetch;prerenderprefetch: Running (PrefetchNotFinishedInTime), Success (PrefetchResponseUsed); prerender: Pending, Running, ReadyChrome loaded the whole page in a hidden tab, seconds before the tap. The tap only showed it.
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:
{ "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_matchestests 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:
// 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: falseandnotAccount: /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.
The fix is a better condition:
{ "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.
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:
{ "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:
// 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 msand414 ms: asked at 212.3 ms.
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:
{
"prerender": [{
"where": { "href_matches": "/shop/*" },
"eagerness": "moderate"
}]
}271 ms213.9 ms270 ms219.3 msChrome asked for the page while the pointer rested on the link, in all 2 tries.
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.
| Eagerness | Prefetches | Prerenders | When the limit is reached |
|---|---|---|---|
immediate | 50 at most. | 10 at most. | New ones don't start while the limit is reached. |
eager | 2 at most. | 2 at most. | The oldest one is canceled to make room. |
moderate | 2 at most. | 2 at most. | The oldest one is canceled to make room. |
conservative | 2 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.
Rules in an HTTP header
Rules don't have to sit in the HTML. A response header can point at a file of rules instead. That helps when the HTML is hard to change: for example, when a CDN, the network of servers that delivers a site's pages, adds the rules.
A shop seals a parcel. The courier wants to add delivery notes, but it can't open the box. So it puts a sticker on the outside: "Notes for this parcel are on our website." Whoever gets the parcel reads the sticker and looks the notes up.
- In real life: The sealed parcel
- In JavaScript: The page's HTML, unchanged
- In real life: The courier's sticker
- In JavaScript: The Speculation-Rules header
- In real life: The notes it points to
- In JavaScript: The rule file, /rules/shop.json
- In real life: The courier
- In JavaScript: A server or CDN setting that adds headers
Ravi moves his rule out of the page. The reviews page now arrives with one more header:
HTTP/1.1 200 OKContent-Type: text/html; charset=utf-8Speculation-Rules: "/rules/shop.json"Line 3 is the Speculation-Rules header. Its value is the address of the rule file, in double quotes. It's a structured header: a header whose value follows a strict grammar. This one is a list of strings, so the quotes are required. Here is the file it points at:
HTTP/1.1 200 OKContent-Type: application/speculationrules+json { "prerender": [ { "urls": ["/shop/mint-tea"] } ]}- Line 2 is the file's content type: the header that says what kind of file it is. It must be
application/speculationrules+json. - Lines 4 to 8 are the same rule as before.
In the recording, Chrome asked for the rule file 175.4 ms after it asked for the reviews page. Then it prerendered the Mint tea page, and Asha's tap showed it. LCP was 26.6 ms after she opened it.
The course also sent the same file as application/json. Chrome fetched it, then ignored it. Nothing was prerendered, and the tap loaded the page from the server: LCP 448 ms.
Two more details from Chrome's docs. URLs in the file are read relative to the file, unless a rule says "relative_to": "document". And a rule can carry a tag. Chrome sends it to the server in a Sec-Speculation-Tags header, so a CDN can tell its own rules from yours.
Why it matters: a header lets a CDN add speculation to every page without changing the HTML. Check the content type, because Chrome drops a file with the wrong one.
No-Vary-Search and duplicate prerenders
Ravi wants to know which link sells more tea. So he adds a query string to each link: the part of an address after ?. The tools link becomes /shop/mint-tea?from=tools. A new footer link is /shop/mint-tea?from=footer. Each name=value pair is a search parameter.
His list rule still prerenders /shop/mint-tea. Asha taps the tools link:
// The list rule prerenders /shop/mint-tea. Asha taps /shop/mint-tea?from=tools.// lcp: the Mint tea page's LCP, in ms from when Asha opened it.const withoutHeader = { prerenderUsed: false, lcp: 464 };const withHeader = { prerenderUsed: true, lcp: 30.1 }; console.log(`Without No-Vary-Search: used ${withoutHeader.prerenderUsed}, LCP ${withoutHeader.lcp} ms`);console.log(`With No-Vary-Search: used ${withHeader.prerenderUsed}, LCP ${withHeader.lcp} ms`);- Line 3 is the page as it was. Chrome didn't use the prerender, and loaded the page from the server: LCP 464 ms.
- Line 4 is the page with the header below. The prerender was used: LCP 30.1 ms.
- Lines 6 and 7 print
Without No-Vary-Search: used false, LCP 464 msandWith No-Vary-Search: used true, LCP 30.1 ms.
To Chrome, /shop/mint-tea and /shop/mint-tea?from=tools are different addresses. It can't know that from changes nothing. Ravi's server can say so, with a header on the Mint tea page:
HTTP/1.1 200 OKContent-Type: text/html; charset=utf-8No-Vary-Search: params=("from")Line 3 is No-Vary-Search. It lists the search parameters that don't change the page. params=("from") means "this page is the same, whatever from says".
Next, Ravi swaps his list rule for a document rule. It picks every /shop/ link, at once. Both links match. Chrome can't read a header before the response arrives, so it treats them as two pages. It prerenders both.
Two waiters hand the cook two slips: "mint tea, table 4" and "mint tea, window table". The cook makes two teas, though the table doesn't change the tea. A sign on the kitchen wall would help, but only once the cook walks over and reads it. Better: the waiter says so with the first slip.
- In real life: Two slips for the same tea
- In JavaScript: /shop/mint-tea?from=tools and ?from=footer
- In real life: The table number
- In JavaScript: The from search parameter
- In real life: The sign on the kitchen wall
- In JavaScript: No-Vary-Search, read when a response arrives
- In real life: The waiter's word, with the first slip
- In JavaScript: expects_no_vary_search, in the rule
The waiter's word is a hint in the rule:
{ "prerender": [{ "where": { "href_matches": "/shop/*" }, "eagerness": "immediate", "expects_no_vary_search": "params=(\"from\")" }]}Line 5 is expects_no_vary_search. It tells Chrome, before any response arrives, which No-Vary-Search header to expect. The quotes inside it are escaped with \, because the whole value is a JSON string.
// A document rule matches both links: ?from=tools and ?from=footer.// requests: speculative requests for the Mint tea page. prerenders: pages Chrome built.const withoutHint = { requests: 2, prerenders: 2 };const withHint = { requests: 2, prerenders: 1 }; console.log(`Without the hint: ${withoutHint.requests} requests, ${withoutHint.prerenders} prerenders`);console.log(`With the hint: ${withHint.requests} requests, ${withHint.prerenders} prerender`);- Line 3 is the rule without the hint: 2 requests to the server, and 2 prerendered pages.
- Line 4 is the rule with it: still 2 requests, but 1 prerender.
- Lines 6 and 7 print
Without the hint: 2 requests, 2 prerendersandWith the hint: 2 requests, 1 prerender.
With the hint, Chrome 157 skipped the second prerender, as its source code says it should. It still fetched both addresses. Either way, Asha's tap used a prerender.
One catch, from Chrome's docs. A page prerendered as ?from=footer can be shown for a ?from=tools tap. Its address changes as it's shown. So read search parameters after the page is shown, not before.
Why it matters: tracking parameters like from are on links everywhere. Without No-Vary-Search, each one can turn a good guess into a wasted prerender.
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:
// 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.prerenderingtrue, 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.andLoaded 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.
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, andprint()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:
GET /shop/mint-tea HTTP/1.1Sec-Purpose: prefetch;prerenderLine 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:
// 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: 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:
// 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 viewsandCounts 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: 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 onprerenderingchange, 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.
// Ravi's analytics: count a page view as the page loads.
navigator.sendBeacon("/visit", location.pathname);1sent from the hidden page, Sec-Purpose: prefetch;prerender1sent from the hidden page, Sec-Purpose: prefetch;prerenderAsha never opened the Mint tea page, but Ravi's server counted a view in each 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? 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
activationStartis above 0. - Line 5:
deliveryTypeisnavigational-prefetchwhen 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:
// 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";…………Reading this page's navigation entry.
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:
- 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
Sort each job by when it should run on a page that may be prerendered.
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.
What does this print?
const noRules = 475.9;
const prerendered = 42;
console.log(`Prerendering saved ${(noRules - prerendered).toFixed(1)} ms.`);Prerendering saved 433.9 ms. The tap with no rules waited for the server; the prerendered tap only showed a page Chrome had built.
Ravi's list rule has no eagerness key. When does Chrome start speculating on its URL?
immediate: as soon as Chrome reads the rule. Document rules default to conservative, a press on the link.
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?
25.3 ms. On a computer, eager waits only 10 ms, so Chrome asked long before the pointer moved away. Moderate would have waited 200 ms.
Ravi's CDN sends this header, but nothing is speculated. What's missing?
Speculation-Rules: /rules/shop.jsonSpeculation-Rules: "/rules/shop.json"Quotes. Without them, Chrome can't parse the header, and it warns that the value looks like a URL you may need to enclose in quotation marks.
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?
Ready: Chrome has prerendered product.html and is waiting for a tap. Tap the shop link, and the Speculative loads tab on the new page says it was prerendered. The course's recorder got the same status, Ready, before each prerendered tap.
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?
// Ravi's "recently viewed" list: his server adds the tea when this runs.
fetch("/recently-viewed", { method: "POST", body: "mint-tea" });// Add the tea only once Asha sees the page.
function addToRecent() {
fetch("/recently-viewed", { method: "POST", body: "mint-tea" });
}
if (document.prerendering) {
document.addEventListener("prerenderingchange", addToRecent, { once: true });
} else {
addToRecent();
}The call moves into a function. If the page is prerendering, it runs on prerenderingchange, once. On a normal visit, it runs straight away. Asha's list only changes when she sees the tea.
Check your understanding
For each question, ask what Chrome does before the tap, and what waits for the visitor.
Question 1 of 7What does the first line of the opening example print?
Read the code, then predict// 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.
Question 2 of 7A document rule has no eagerness key. When does Chrome speculate on its links?
Choose an answer to see the explanation.
Question 3 of 7What does a prerender do that a prefetch doesn't?
Choose an answer to see the explanation.
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.
Question 5 of 7A rule file is sent with Content-Type: application/json. What happens?
Choose an answer to see the explanation.
Question 6 of 7Why add expects_no_vary_search to a document rule?
Choose an answer to see the explanation.
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) orconservative(a press). Chrome keeps 2 of each, except immediate. - The
Speculation-Rulesheader points at a rule file: quote the URL, and serve it asapplication/speculationrules+json. No-Vary-Searchlets one prerender serve other query strings.expects_no_vary_searchstops duplicates.- Hold side effects and analytics until
prerenderingchange. Measure withactivationStartanddeliveryType.
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:
- HTML Standard: speculation rules, WHATWG.
- Prerender pages in Chrome for instant page navigations, Chrome for Developers.
- Prerendering Revamped, WICG.
- performance_navigation_timing.cc, lines 225 to 230: deliveryType navigational-prefetch, Chromium source.
- speculation_rule_set.cc, lines 412 to 416: the default eagerness of each kind of rule, Chromium source.
- document_speculation_rules.cc, lines 921 to 931: links to a spot on the same page are skipped, Chromium source.
- HTML Standard: speculative loading security, WHATWG.
- HTML Standard: speculation rule eagerness, WHATWG.
- anchor_element_interaction_tracker.h, lines 113 to 114: moderate waits 200 ms, Chromium source.
- features.cc, lines 1801 to 1813: eager waits 10 ms, on computers, Chromium source.
- prefetch_params.h, lines 113 to 116: 50 immediate prefetches, 2 conservative, Chromium source.
- prefetch_features.cc, lines 98 to 104: 2 eager and 2 moderate prefetches, Chromium source.
- prerender_host_registry.h, lines 93 to 94: 10 immediate prerenders, 2 others, Chromium source.
- prerender_host_registry.cc, lines 1995 to 2016: at the limit, the oldest is canceled, Chromium source.
- prerender_host_registry.cc, lines 601 to 648: settings, battery saver and memory, Chromium source.
- HTML Standard: the Speculation-Rules header, WHATWG.
- speculation_rules_header.cc, lines 59 to 75: the header is a list of quoted strings, Chromium source.
- The No-Vary-Search HTTP Caching Extension, IETF HTTP Working Group.
- prerender_host_registry.cc, lines 725 to 744: duplicate prerenders and the hint, Chromium source.
- Debugging speculation rules, Chrome DevTools docs.
- Preload.pdl, lines 207 to 215: the statuses DevTools reports, Chromium source.
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.