Prefetching strategies
Choose which next pages to prefetch: links on screen, the link under the pointer, or the pages your data predicts. Count what wrong guesses cost, and respect Save-Data.
- 01Pick a way to guessPrefetch links on screen, the link under the pointer, or the pages your analytics predict, and know what your framework does.
- 02Count the cost of a guessWork out the hit rate and the wasted bytes of each strategy, and see why a prerender costs far more than a prefetch.
- 03Respect Save-DataKnow where Save-Data comes from, what Chrome skips by itself, and how your page and server can skip the rest.
Which tea will Asha open next?
Ravi's shop has a new page: a list of all eight teas, best sellers first. In lesson 33.2, one rule made the Mint tea page appear at once. That was easy. The reviews page had one shop link. The list has eight.
Which pages should Chrome fetch before Asha taps? Ravi tries the simplest answer first: every tea she can see. Here is her tap on Mint tea, first with no prefetching, then with it:
Here are the two taps as code:
// Asha taps Mint tea on Ravi's list. When was its photo on screen?// In ms after her tap: the middle of 5 tries, from Chrome's own screenshots.const noPrefetching = { onScreen: 712.8, fetchedFirst: 0 };const everyTeaOnScreen = { onScreen: 301.1, fetchedFirst: 6 }; console.log(`No prefetching: ${noPrefetching.onScreen} ms, ${noPrefetching.fetchedFirst} pages fetched first.`);console.log(`Every tea on screen: ${everyTeaOnScreen.onScreen} ms, ${everyTeaOnScreen.fetchedFirst} pages fetched first.`);- Lines 1 and 2 are comments. The course tapped with a mouse, 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 Fast 4G, as in lesson 33.2. Each answer waited 165 ms. Building a tea page took Ravi's server 250 ms more.
- Line 3 is the tap with no prefetching. Line 4 is the tap with every tea on screen fetched first.
- Lines 6 and 7 print
No prefetching: 712.8 ms, 0 pages fetched first.andEvery tea on screen: 301.1 ms, 6 pages fetched first.
The photo came 411.7 ms sooner. But Chrome fetched six pages to win that one tap, and Asha opened one of them. Was that a good deal? It depends on which pages you guess, and on who pays for the rest.
To prefetch a page is to fetch it before the visitor asks for it. A prefetching strategy is how you choose which pages, and when. This lesson compares three: the links on screen, the link under the pointer, and the pages your data says come next.
A baker opens at seven. She can bake one of every loaf in the window, so nobody waits. She can start a loaf when a customer lingers at the counter. Or she can bake last week's two best sellers. Every loaf nobody buys is flour and time thrown away.
- In real life: Baking one of every loaf in the window
- In JavaScript: Prefetching every link on screen
- In real life: Starting a loaf when someone lingers
- In JavaScript: Prefetching the link the pointer rests on
- In real life: Baking last week's best sellers
- In JavaScript: Prefetching the pages your analytics predict
- In real life: A loaf nobody buys
- In JavaScript: A page fetched for nothing: data, battery and server work
Prefetching trades the visitor's data for time. A good strategy fetches the pages people really open next. It fetches nothing for a visitor who asked to save data. This lesson measures each guess: the time it saved, and what it wasted.
The basics are in Prefetching and preloading data and, for Next.js, in Instant navigations and partial prefetching. This lesson measures the choices.
Guessing from the screen
A link on screen is a link Asha might tap. A link far below isn't, yet. So Ravi watches the screen. When a tea's link comes into view, he asks Chrome to prefetch its page.
The visible part of a page is the viewport. To know when an element enters it, a page uses an IntersectionObserver. It's an object that calls your function when an element comes into view or leaves it. Here is Ravi's script. It's the idea behind quicklink, a small library from Google Chrome Labs.
// Ravi's viewport prefetching: each tea link, once it's on screen.const observer = new IntersectionObserver((entries) => { for (const entry of entries) { if (!entry.isIntersecting) continue; observer.unobserve(entry.target); const rules = document.createElement("script"); rules.type = "speculationrules"; rules.textContent = JSON.stringify({ prefetch: [{ urls: [entry.target.href] }] }); document.body.append(rules); }});for (const link of document.querySelectorAll(".tea a")) observer.observe(link);- Line 2 makes the observer. Chrome calls its function with a list of entries, one for each link that came into view or left.
- Line 4 skips a link that isn't on screen.
- Line 5 stops watching that link, so each tea is fetched once.
- Lines 6 to 9 add a speculation rule for that one address, like the rules in lesson 33.2. Chrome reads the new rule and prefetches the page.
- Line 12 starts watching every tea link.
Asha's screen showed six teas. Rooibos and Hibiscus sat below its bottom edge. The script asked for the six on screen as soon as the list loaded:
// The pages Chrome fetched for the viewport script, before Asha's tap.const fetched = ["mint-tea", "green-tea", "chamomile", "black-tea", "jasmine", "oolong"];const opened = "mint-tea";const neverOpened = fetched.filter((page) => page !== opened); console.log(`Fetched ${fetched.length}, used 1, never opened ${neverOpened.length}.`);- Line 2 lists the six pages Chrome fetched, in order.
- Line 3 is the page Asha opened. Line 4 keeps the pages she never opened.
- Line 6 prints
Fetched 6, used 1, never opened 5.
Chrome didn't fetch all six at once. It fetched three, then the next three once those had arrived. On a computer, Chrome's source code runs at most three prefetches at a time.
Look at the opening picture again. With the prefetch, the words appeared 51.1 ms after the tap. The photo took another 250 ms. A prefetch gets only the HTML. The photo can't start until the page asks for it, after the tap.
On a phone, Chrome can watch the screen by itself. A speculation rule with eager eagerness fires once a link has been on screen for 50 ms. A moderate rule picks a big link near your last touch, after you stop scrolling. Chrome's source runs these phone rules on Android. On a computer, it runs them only while DevTools pretends to be a phone.
quicklink itself adds a few limits that Ravi's script lacks. It waits until the browser is idle. It skips slow connections. And it can stop after a set number of links, or fetch only links that stay on screen for a while.
Why it matters: the screen shows many links, and Asha taps one. Here, five of six guesses were wasted.
Guessing from the pointer
On a computer, there's a better sign than the screen: the mouse pointer. People often rest the pointer on a link just before they click it. Lesson 33.2's moderate eagerness waits for exactly that, a rest of 200 ms.
A good shop assistant doesn't follow everyone who walks past the shelves. When you stop at one tea, she fetches a fresh tin from the back. By the time you reach the till, it's ready.
- In real life: Customers walking past the shelves
- In JavaScript: The pointer passing over links
- In real life: Stopping at one tea
- In JavaScript: Resting the pointer on a link for 200 ms
- In real life: Fetching a tin from the back
- In JavaScript: Chrome prefetching that one page
- In real life: Reaching the till
- In JavaScript: The tap
Ravi's rule picks every tea, at moderate:
{ "prefetch": [{ "where": { "href_matches": "/shop/*" }, "eagerness": "moderate" }]}Line 2 asks for a prefetch, not a prerender. Line 3 picks every link whose address starts with /shop/. Line 4 sets the eagerness.
The course moved the pointer the way a person might. It stopped on Jasmine and on Black tea for 100 ms each. Then it rested on Mint tea, for 300 ms in one test and 700 ms in another, and tapped. Chrome fetched nothing for Jasmine or Black tea. It asked only for Mint tea:
// The pointer rests on Mint tea, then Asha taps. In ms after the pointer arrived.// asked: Chrome asked for the page. arrived: all of it had come. tap: Asha tapped.const rests = [ { asked: 203.2, arrived: 619.8, tap: 307 }, { asked: 203, arrived: 619.6, tap: 707.6 },];for (const rest of rests) console.log(`Tap at ${rest.tap} ms: ${Math.max(0, rest.arrived - rest.tap).toFixed(1)} ms left to wait.`);- Lines 4 and 5 are the two rests, from the first try of each.
- In both, Chrome asked for the page about 203 ms after the pointer arrived. All of it had come about 620 ms after.
- Line 7 prints
Tap at 307 ms: 312.8 ms left to wait.andTap at 707.6 ms: 0.0 ms left to wait.
The tap at 307 ms came while the page was still on its way. Chrome didn't ask the server again. It waited for the prefetch it had started. So the 300 ms rest won back part of the wait: the photo was on screen 610.7 ms after the tap, not 712.8 ms. The 700 ms rest won all of it: 302.8 ms.
Lesson 33.2's conservative eagerness waits even longer, for the press itself. It fetches only a link Asha has started to tap, so it almost never wastes a page. But the head start is only the time between pressing the button and letting go.
Why it matters: hover fetched one page, and Asha used it. But it helps only someone who rests the pointer long enough, and a phone has no pointer to rest.
Guessing from data
Ravi has a third clue: what earlier visitors did. His analytics count where people go after the list.
// Ravi's analytics: where 100 visits to the list went next.const next = { "mint-tea": 45, "green-tea": 20, chamomile: 8, "black-tea": 7, jasmine: 6, oolong: 4, rooibos: 2, hibiscus: 1, left: 7 };const teas = Object.entries(next).filter(([page]) => page !== "left");const top = teas.sort((a, b) => b[1] - a[1]).slice(0, 2); console.log(`Prefetch: ${top.map(([page]) => page).join(", ")}`);console.log(`They cover ${top[0][1] + top[1][1]} of 100 visits.`);- Line 2 holds his counts for 100 visits: 45 opened Mint tea next, 20 opened Green tea, and so on. 7 left the shop.
- Line 3 drops the visitors who left. Line 4 sorts the teas, most visits first, and keeps the top two.
- Lines 6 and 7 print
Prefetch: mint-tea, green-teaandThey cover 65 of 100 visits.
So Ravi names those two in a list rule. Lesson 33.2 showed that a list rule starts as soon as Chrome reads it:
{ "prefetch": [ { "urls": ["/shop/mint-tea", "/shop/green-tea"] } ]}Line 3 lists the two addresses. Chrome fetched both as the list loaded. Asha tapped Mint tea, and its photo was on screen 295.3 ms after the tap. That's as fast as the viewport script, for two pages instead of six.
A prediction can miss. In another test, Asha tapped Jasmine. Both guesses were wasted. Jasmine loaded the normal way, with the full wait for Ravi's server.
Data and a sign also work together. Chrome's docs say a list rule can take an eagerness too. On a computer, with moderate, Chrome fetches one of the rule's pages only when the pointer rests on a link to it. Ravi could name his top four teas, and fetch only the one Asha points at.
Tools can make the prediction for you. Guess.js was built for this: it read Google Analytics data and prefetched the likely next pages. It's still labelled alpha, and it hasn't had a release since 2020. A short list kept by hand, like Ravi's, does the same job. Someone just has to update it when visitors change.
Try each way of guessing that the course recorded. Each one shows what the list fetched before the tap, and how soon the photo appeared:
// Ravi's viewport prefetching: each tea link, once it's on screen.
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
observer.unobserve(entry.target);
const rules = document.createElement("script");
rules.type = "speculationrules";
rules.textContent = JSON.stringify({ prefetch: [{ urls: [entry.target.href] }] });
document.body.append(rules);
}
});
for (const link of document.querySelectorAll(".tea a")) observer.observe(link);Mint teaMint tea, Green tea, Chamomile, Black tea, Jasmine, Oolong7.0 kB5.8 kBMint tea61.9 ms after the tap301.1 msThe script asked for every tea on screen. Asha used one of them; the rest were fetched for nothing.
Why it matters: data finds the few pages most visitors open. Check it again now and then, because last month's best seller may change.
Framework link prefetching
Many sites never write a rule. Their framework's link component guesses for them.
A new washing machine has twenty programmes. Most people just press Start, and it runs the default every time. Whoever chose that default decided how most clothes get washed.
- In real life: The default programme
- In JavaScript: The framework's prefetching, as it comes
- In real life: Just pressing Start
- In JavaScript: Using its link component with no settings
- In real life: Picking another programme
- In JavaScript: Changing a link's prefetch setting
- In real life: The maker who chose the default
- In JavaScript: The framework's authors
Next.js is a common case. Its <Link> component prefetches by itself:
// Next.js: a Link prefetches its page once it comes near the screen, in production.<Link href="/shop/mint-tea">Mint tea</Link> // A link in a very long list: never prefetched, on screen or on hover.<Link href="/shop/hibiscus" prefetch={false}>Hibiscus</Link>- Line 2 is a plain link. In production, Next.js prefetches its page once the link comes near the screen. Its source watches every link with one IntersectionObserver, with a 200 px margin around the screen.
- Line 5 sets
prefetch={false}. That link is never prefetched, on screen or on hover. The Next.js docs suggest it for very long lists.
Two more details from the docs. Prefetching runs only in production, so next dev never shows it. And a hover moves a link's prefetch up the queue. The docs also show how to wait for a hover before prefetching at all. For what a Next.js prefetch holds, see Instant navigations.
That 200 px margin matters on Ravi's list. Rooibos started 2 px below Asha's screen, and Hibiscus 102 px below. Both are inside the margin, so Next.js would have fetched all eight teas.
Other tools pick other defaults. Read the table across: each row is one tool, when it prefetches by default, and what it does for a visitor who asked to save data.
| Tool | When it prefetches, by default | When the visitor asked to save data |
|---|---|---|
Next.js <Link> | When the link comes within 200 px of the screen, in production only. A hover or touch moves it up the queue. | Its App Router code doesn't check. |
Nuxt <NuxtLink> | When the link is on screen, once the browser is idle. | It doesn't prefetch, and not on 2G either. |
| SvelteKit | Its starter project loads a link's data on hover, or on touch on a phone. | It never preloads. |
| Astro | Links you mark, or every link if you ask. On hover, unless you pick another strategy. | It waits for a tap instead. |
| quicklink | Links on screen, once the browser is idle. | It doesn't prefetch, and not on 2G either. |
Chrome's eager rule, on a phone | When the link has been on screen for 50 ms. | Chrome skips every rule when Android's Data Saver is on. |
Why it matters: if you use a framework, you already have a strategy. Find out which one, and check it against your own pages.
What a wrong guess costs
Every guess costs something, even a right one. A wrong guess costs it all for nothing. Three costs add up:
- Data. The bytes come over the visitor's connection, and on many plans they pay for each one. Lesson 1.3 showed how much of their income some people spend on data.
- Server work. Each guess is a page Ravi's server builds: 250 ms of work each time.
- Battery and memory, most of all for a prerender, which runs the page's scripts out of sight.
You don't know which bus will come first. So you buy a ticket for every route at the stop, and never wait to pay. But you ride one bus, and the other tickets go in the bin.
- In real life: A ticket for every route at the stop
- In JavaScript: A prefetch for every link on screen
- In real life: The bus you ride
- In JavaScript: The page the visitor opens
- In real life: Tickets in the bin
- In JavaScript: Pages fetched for nothing
- In real life: The price of each ticket
- In JavaScript: The bytes, server work and battery each guess costs
The hit rate of a strategy is the share of its guesses that were used: pages opened, divided by pages fetched. Here are Asha's taps:
// Before Asha's tap: pages fetched ahead, how many she used, and the bytes for the rest.const strategies = [ { name: "viewport", fetched: 6, used: 1, wastedBytes: 5810 }, { name: "hover", fetched: 1, used: 1, wastedBytes: 0 }, { name: "predicted", fetched: 2, used: 1, wastedBytes: 1167 },];for (const s of strategies) console.log(`${s.name}: hit rate ${Math.round((s.used / s.fetched) * 100)}%, ${s.wastedBytes} bytes wasted`);- Lines 3 to 5 hold what each strategy fetched before the tap, how many pages Asha used, and the bytes for the rest.
- Line 8 divides the pages used by the pages fetched, and turns it into a percentage.
- It prints
viewport: hit rate 17%, 5810 bytes wasted,hover: hit rate 100%, 0 bytes wastedandpredicted: hit rate 50%, 1167 bytes wasted.
Ravi's tea pages are small, about 1.2 kB of HTML each. So five wasted prefetches cost Asha only 5.8 kB, and cost Ravi's server five builds. A prerender is different. The same script, asking for prerenders, loaded each tea's photo too:
// The viewport script, asking for prefetches, then for prerenders.const prefetch = { bytesFirst: 6974, onScreen: 301.1 };const prerender = { bytesFirst: 450890, onScreen: 47.8 }; const times = Math.round(prerender.bytesFirst / prefetch.bytesFirst);console.log(`Prerender: ${times} times the bytes, ${(prefetch.onScreen - prerender.onScreen).toFixed(1)} ms sooner.`);- Line 2 is the prefetching script: 6,974 bytes before the tap, and the photo on screen at 301.1 ms.
- Line 3 is the prerendering script: 450,890 bytes, and 47.8 ms.
- Line 6 prints
Prerender: 65 times the bytes, 253.3 ms sooner.
Of those bytes, 346.9 kB were for teas Asha never opened. That's more than three whole Mint tea photos.
Read the table across: each row is one way of guessing, what it fetched before the tap, and how soon the photo appeared after it.
| How Ravi guessed | Fetched before the tap | Bytes before the tap | Bytes for teas she never opened | Photo on screen after the tap |
|---|---|---|---|---|
| No prefetching. | 0 pages. | 0 kB. | 0 kB. | 712.8 ms. |
| Every tea on screen. | 6 pages. | 7.0 kB. | 5.8 kB. | 301.1 ms. |
| Every tea on screen, as prerenders. | 6 pages and their photos. | 450.9 kB. | 346.9 kB. | 47.8 ms. |
| A 300 ms rest on Mint tea. | 1 page. | 1.2 kB. | 0 kB. | 610.7 ms. |
| A 700 ms rest on Mint tea. | 1 page. | 1.2 kB. | 0 kB. | 302.8 ms. |
| The top two teas. | 2 pages. | 2.3 kB. | 1.2 kB. | 295.3 ms. |
| The top two teas, but Asha taps Jasmine. | 2 pages. | 2.3 kB. | 2.3 kB. | No faster than no prefetching. |
One visit is small. A day of visits isn't. Type how many visits Ravi's list gets, and see each strategy's waste grow:
// For each way of guessing: Asha's recorded visit, times the visits.
const fetchedAhead = visit.fetched * visits;
const wastedBytes = visit.wastedBytes * visits;
const builtForNothing = visit.unusedPages * visits;6,0005.8 MB5,0006,000346.9 MB5,0001,0000 MB02,0001.2 MB1,000Each visit fetches what Asha's did. The waste is the bytes and the server builds for teas nobody on that visit opened.
Chrome's limits from lesson 33.2 help a little. On a computer, it keeps only two moderate or eager speculations per page. But a script that adds immediate rules, like Ravi's, can reach Chrome's limit of 50 prefetches.
On a real site, you can count the hit rate yourself. Every guess reaches your server with a Sec-Purpose: prefetch header, as lesson 33.2 showed. Every page opened from a guess says navigational-prefetch in its deliveryType. Divide the second count by the first.
Why it matters: count your hit rate before you widen a guess. If it's low, guess fewer pages, or prefetch instead of prerender.
Respecting Save-Data
Some visitors ask to use less data. On an Android phone, the setting is called Data Saver. When it's on, Chrome tells every site, in two ways:
- The Save-Data header. Chrome adds
Save-Data: onto its requests. A server doesn't have to ask for it. navigator.connection.saveData, which is true for the page's own scripts.
Some people put a sticker on their letterbox: "No flyers, please." The postman still brings their letters. He just leaves out the paper they never asked for.
- In real life: The sticker on the letterbox
- In JavaScript: Save-Data: on, and saveData true
- In real life: Letters the person is waiting for
- In JavaScript: The pages the visitor opens
- In real life: Flyers
- In JavaScript: Prefetches: pages nobody asked for yet
- In real life: A postman who reads the sticker
- In JavaScript: Chrome, your server and your scripts checking Save-Data
saveData, and Chrome stops its own guesses.Chrome itself listens. While Data Saver is on, its source treats preloading as switched off. It makes no prefetch and no prerender. The switch is Android's: on a computer, Chrome's Data Saver check always says no.
On a computer, DevTools can still do two smaller things. It can add Save-Data: on to the page's requests, and it can make navigator.connection.saveData true. The course did both, on three versions of the list:
// DevTools told the list that Asha asked to save data. 2 visits each.// The numbers: pages Chrome fetched ahead of time.const rulesAsTheyAre = [2, 2];const serverLeavesRulesOut = [0, 0];const scriptChecksSaveData = [0, 0]; console.log(`Rules as they are: ${rulesAsTheyAre.join(" and ")}`);console.log(`Server leaves rules out: ${serverLeavesRulesOut.join(" and ")}`);console.log(`Script checks saveData: ${scriptChecksSaveData.join(" and ")}`);- Line 3 is Ravi's rule as it was. Chrome still fetched both teas. DevTools had changed what the page saw, not Chrome's own switch.
- Line 4 is Ravi's server reading the header and leaving the rule out. Nothing was fetched.
- Line 5 is the viewport script, checking first. Nothing was fetched.
- It prints
Rules as they are: 2 and 2,Server leaves rules out: 0 and 0andScript checks saveData: 0 and 0.
Here is the check in Ravi's script. Only line 4 changed:
// Ravi's viewport prefetching: each tea link, once it's on screen.const observer = new IntersectionObserver((entries) => { for (const entry of entries) { if (!entry.isIntersecting || navigator.connection?.saveData) continue; observer.unobserve(entry.target); const rules = document.createElement("script"); rules.type = "speculationrules"; rules.textContent = JSON.stringify({ prefetch: [{ urls: [entry.target.href] }] }); document.body.append(rules); }});for (const link of document.querySelectorAll(".tea a")) observer.observe(link);Line 4 now also skips the link when navigator.connection?.saveData is true. The ?. keeps it safe in Firefox and Safari, which have no navigator.connection.
And here is Ravi's server:
// Ravi's server: no guesses for a visitor who asked to save data.const saveData = request.headers["save-data"] === "on";response.setHeader("Vary", "Save-Data");response.end(saveData ? listWithoutRules : listWithRules);- Line 2 reads the request's Save-Data header.
- Line 3 adds
Vary: Save-Data. Lesson 15.1 metVary: it tells caches that this header changes the answer, so a CDN keeps the two lists apart. - Line 4 sends the list without rules to a visitor who asked to save data.
On a real phone with Data Saver on, Chrome would skip Ravi's speculation rules anyway. So the checks matter most for prefetching Chrome doesn't control: a script that calls fetch(), and most framework prefetches. The table in the last section showed which tools check. Next.js's App Router doesn't.
Many tools also skip a 2G connection, from navigator.connection.effectiveType. Both values live on navigator.connection, the Network Information API, which only Chromium-based browsers have. Does your browser ask to save data?
// What this lab reads, in your browser.
const connection = navigator.connection;
const saveData = connection?.saveData;
const slow = /2g/.test(connection?.effectiveType ?? "");
const wouldPrefetch = !saveData && !slow;………Reading navigator.connection.
Lines 2 to 5 of the lab's code read the connection, and decide whether Ravi's code would prefetch for you.
Why it matters: a visitor with Data Saver on is telling you that bytes cost them. Guesses are the first bytes to drop.
Which guess for which link?
Each link below is on one of Ravi's pages. Sort it by how Ravi should guess it:
- Mint tea, opened after 45 of every 100 visits to the list
- Page 2 of the reviews, for a reader at the end of page 1
- Every tea in a list of 200 teas
- The 30 links in the site's footer
- Sign out
- A link that adds a tea to the cart
- Any link, for a visitor who turned on Save-Data
- A 40 MB video download
Sort each link by how Ravi should prefetch it.
Common mix-ups
- "Prefetching every link on screen is free." No. Asha used one page of six. The other five cost her data and cost Ravi's server five builds.
- "A prefetched page appears at once." No. A prefetch gets the HTML. The photo still loaded after the tap, 250 ms more.
- "Hover prefetching only helps if the page arrives before the click." No. Chrome waits for a prefetch on its way. A 300 ms rest still brought the photo sooner.
- "Speculation rules ignore Save-Data." No. While Android's Data Saver is on, Chrome makes no prefetch and no prerender.
- "If DevTools makes saveData true, Chrome stops speculating." No. DevTools changes what the page sees. Chrome's own switch is Android's setting.
- "You can test Next.js prefetching with next dev." No. Viewport prefetching runs only in production.
Practice exercises
Answer first, then use the hints.
With a 200 px margin around the screen, Ravi's list would fetch all eight teas. What does this print?
const fetched = 8; // every tea, with a 200 px margin around the screen
const used = 1;
console.log(`Hit rate: ${Math.round((used / fetched) * 100)}%`);Hit rate: 13%. With a 200 px margin, as Next.js uses, all eight teas count as near the screen, and Asha still opens one.
What does this print?
const noPrefetching = 712.8;
const rest300 = 610.7;
console.log(`Resting 300 ms saved ${(noPrefetching - rest300).toFixed(1)} ms.`);Resting 300 ms saved 102.1 ms. Chrome asked at about 203 ms, so the page had a head start of about 100 ms when Asha tapped.
In the playground with seven ways to guess, pick the wrong guess. How many ms after the tap did Jasmine's HTML start arriving?
419.3 ms after the tap: the full wait for the network and Ravi's server. The two guesses were for other teas, so they didn't help.
Ravi's old prefetcher fetches a tea's page when the pointer comes onto its link. Make it skip visitors who asked to save data. What do you check?
// Ravi's old prefetcher: fetch a tea's page when the pointer comes onto its link.
for (const link of document.querySelectorAll(".tea a")) {
link.addEventListener("pointerenter", () => fetch(link.href), { once: true });
}// The same, but never for a visitor who asked to save data.
for (const link of document.querySelectorAll(".tea a")) {
link.addEventListener("pointerenter", () => {
if (navigator.connection?.saveData) return;
fetch(link.href);
}, { once: true });
}Check navigator.connection?.saveData before the fetch(). When it's true, return without fetching. The ?. keeps the code safe in browsers without navigator.connection.
Open this copy of Ravi's list in Chrome. Its rule prefetches mint-tea.html and green-tea.html. Open DevTools and find the speculation for green-tea.html. What status does it show?
Ready: Chrome has fetched green-tea.html and is keeping it for a tap. The course's recorder saw the same status for Green tea before every tap on Mint tea.
Asha turns on Data Saver on her Android phone. Ravi's list has his speculation rule for the top two teas, and the old fetch() prefetcher from exercise 4, without the fix. Which one still downloads pages?
The fetch() prefetcher. Chrome skips the speculation rule by itself while Data Saver is on. The old prefetcher's fetch() still runs, unless the script checks saveData, as in exercise 4.
Check your understanding
For each question, ask what was fetched before the tap, and who paid for it.
Question 1 of 7What does the second line of the opening example print?
Read the code, then predict// Asha taps Mint tea on Ravi's list. When was its photo on screen? // In ms after her tap: the middle of 5 tries, from Chrome's own screenshots. const noPrefetching = { onScreen: 712.8, fetchedFirst: 0 }; const everyTeaOnScreen = { onScreen: 301.1, fetchedFirst: 6 }; console.log(`No prefetching: ${noPrefetching.onScreen} ms, ${noPrefetching.fetchedFirst} pages fetched first.`); console.log(`Every tea on screen: ${everyTeaOnScreen.onScreen} ms, ${everyTeaOnScreen.fetchedFirst} pages fetched first.`);Choose an answer to see the explanation.
Question 2 of 7On a computer, Ravi's moderate rule picks every tea. Asha's pointer stops on Jasmine for 100 ms, then moves on. What does Chrome fetch?
Choose an answer to see the explanation.
Question 3 of 7A speculation rules prefetch got the Mint tea page's HTML before the tap. What still waited for the tap?
Choose an answer to see the explanation.
Question 4 of 7The viewport script fetched 6 tea pages, and Asha opened one. What was its hit rate?
Choose an answer to see the explanation.
Question 5 of 7Asha's Android phone has Data Saver on. What does Chrome do with Ravi's speculation rules?
Choose an answer to see the explanation.
Question 6 of 7Which prefetch value stops a Next.js Link from prefetching, both on screen and on hover?
Choose an answer to see the explanation.
Question 7 of 7In the course's test, DevTools set saveData to true, yet Ravi's speculation rule still fetched two pages. Why?
Choose an answer to see the explanation.
Key takeaways
- Prefetching trades the visitor's data for time. A strategy decides which pages to fetch, and when.
- The screen gives many guesses and few hits: one page used of six. The pointer gives few guesses and many hits, on computers only. Data picks the pages most visitors open.
- A prefetch gets only the HTML. A prerender gets the whole page, for many times the bytes: 65 times here.
- The hit rate is pages used divided by pages fetched. Measure it before you widen a guess.
- Frameworks guess for you. Next.js prefetches every link near the screen, in production only.
- With Data Saver on, Chrome skips its own guesses. Your server should read
Save-Data, and your scriptsnavigator.connection.saveData.
Remember the one-liner.
Guess the pages people really open next, count what each guess wastes, and guess nothing for a visitor who asked to save data.
Module 33, looking back
This lesson ends Module 33. In lesson 33.1, the back/forward cache made Back instant: Chrome kept the page Asha left. In lesson 33.2, speculation rules made the next page instant: Chrome loaded it before the tap. In this lesson, you chose which next pages are worth that cost.
Sources
The facts on this page come from these specs, docs and source files:
- HTML Standard: speculation rules, WHATWG.
- quicklink, Google Chrome Labs.
- prefetch_features.cc, lines 79 to 93: three prefetches at a time on a computer, Chromium source.
- prefetch_scheduler.cc, lines 33 to 46: the limit on prefetches running at once, Chromium source.
- Prerender pages in Chrome for instant page navigations, Chrome for Developers.
- anchor_element_interaction_tracker.cc, lines 128 to 141: the phone's viewport rules, Chromium source.
- anchor_element_interaction_tracker.cc, lines 664 to 706: links that come on screen, Chromium source.
- features.cc, lines 1799 to 1824: hover on computers, 50 ms on screen, Chromium source.
- Guess.js, Guess.js authors.
- guess-webpack: versions, npm.
- Link component: prefetch, Next.js docs.
- Prefetching, Next.js docs.
- links.ts, lines 121 to 127: one observer, with a 200 px margin, Next.js source, 16.4.6.
- links.ts, lines 271 to 277: no viewport prefetching in development, Next.js source, 16.4.6.
- types.ts, lines 12 to 32: a hovered link's prefetch goes first, Next.js source, 16.4.6.
- route-loader.ts, lines 399 to 406: the Pages Router skips Save-Data and 2G, Next.js source, 16.4.6.
- NuxtLink: prefetch links, Nuxt docs.
- prefetch-util.ts, lines 7 to 17: no prefetch on Save-Data or 2G, Nuxt source, 4.6.4.
- Link options: data-sveltekit-preload-data, SvelteKit docs.
- Prefetch, Astro docs.
- index.mjs, lines 55 to 70: quicklink checks Save-Data and 2G, quicklink source, 3.0.2.
- prefetch_params.h, lines 113 to 116: at most 50 immediate prefetches, Chromium source.
- Save Data API, WICG.
- Save-Data header, MDN.
- NetworkInformation: saveData, MDN.
- data_saver.cc, lines 57 to 81: Data Saver is Android's setting, Chromium source.
- client_hints.cc, lines 23 to 33: Save-Data is sent without asking, Chromium source.
- client_hints.cc, lines 268 to 275: Save-Data: on, only when it's on, Chromium source.
- preloading_prefs.cc, lines 60 to 77: no preloading with Data Saver, Chromium source.
- prefetch_service.cc, lines 833 to 840: no prefetch when preloading is off, Chromium source.
- Emulation.pdl, lines 578 to 582: DevTools' saveData override, Chromium source.
Coming next: Fast route changes. A single-page app changes pages without loading a new document. You'll see what makes those route changes fast or slow.