completefrontend
Open lab My progress
THE WEB PERFORMANCE FIELD GUIDE

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.

By the end, you can
  • 01
    Pick a way to guessPrefetch links on screen, the link under the pointer, or the pages your analytics predict, and know what your framework does.
  • 02
    Count 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.
  • 03
    Respect 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:

Asha taps Mint tea on Ravi's list twice, in real frames from Chrome. No prefetching: the list stays until 462.8 ms, the words appear, and the photo follows at 712.8 ms. Every tea on screen, prefetched: the list stays until 51.1 ms, the words appear, and the photo follows at 301.1 ms. Beside each row, a bar drawn to scale from the tap to the photo on screen.No prefetchingRavi's list at the tap: Our teas, with Mint tea, Green tea, Chamomile, Black tea, Jasmine and Oolong on screen.462.8 ms after the tap: the Mint tea page's words and price, with an empty space where the photo goes.712.8 ms after the tap: the Mint tea page with its photo.the tap462.8 ms712.8 ms712.8 msEvery tea on screen, prefetchedRavi's list at the tap: Our teas, with Mint tea, Green tea, Chamomile, Black tea, Jasmine and Oolong on screen.51.1 ms after the tap: the Mint tea page's words and price, with an empty space where the photo goes.301.1 ms after the tap: the Mint tea page with its photo.the tap51.1 ms301.1 ms301.1 msthe list, still on screenwords shown, photo loading
Real frames from Chrome, the middle of 5 taps each. Both pages waited about 250 ms for the photo after the words. Prefetching removed the wait before the words.

Here are the two taps as code:

Asha's two tapsPop out in the code editor (opens in a new tab)JavaScript
// 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. and Every 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.

Real-life analogyA baker guessing the morning's orders

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
The main idea

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 prefetchingJavaScript
// 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:

What the script fetched before the tapPop out in the code editor (opens in a new tab)JavaScript
// 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.

Real-life analogyA shop assistant who waits for you to stop

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 the tea the pointer rests onJSON
{  "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:

Two rests on Mint teaPop out in the code editor (opens in a new tab)JavaScript
// 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. and Tap at 707.6 ms: 0.0 ms left to wait.
Two rests on Mint tea, to scale from the moment the pointer arrived. 300 ms rest: Chrome asked for the page at 203.2 ms, all of it had come at 619.8 ms, and Asha tapped at 307 ms, with 312.8 ms left to wait. 700 ms rest: Chrome asked for the page at 203 ms, all of it had come at 619.6 ms, and Asha tapped at 707.6 ms, with nothing left to wait.the pointer arrives300 ms resttap312.8 ms left to wait700 ms resttapnothing left to waitwaiting for a 200 ms restthe page on its way
Chrome waited for a 200 ms rest, then asked. The page took about 417 ms more to arrive. A tap at 300 ms came while it was on its way. A tap at 700 ms found it ready.

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.

Where 100 visits went nextPop out in the code editor (opens in a new tab)JavaScript
// 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-tea and They 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 the two best sellersJSON
{  "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:

Playground: seven ways to guess
What's on the list pageJavaScript
// 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);
ViewportRecorded
Asha tapsMint tea
Fetched before the tapMint tea, Green tea, Chamomile, Black tea, Jasmine, Oolong
Bytes fetched before the tap7.0 kB
Bytes for teas she never opened5.8 kB
Opened from a guessMint tea
Tea pages Ravi's server built6
HTML started arriving1.9 ms after the tap
Photo on screen after the tap301.1 ms
Try it yourself
Viewport

The script asked for every tea on screen. Asha used one of them; the rest were fetched for nothing.

Recorded in Chrome 157, with a CPU 4 times slower and a server that played Fast 4G. Asha read the list for 3 seconds, then tapped. Bytes are what the server sent. The photo time is the middle try's.

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.

Real-life analogyA washing machine's default programme

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:

Two Next.js linksTSX
// 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.

How each tool guesses by default
ToolWhen it prefetches, by defaultWhen 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.
SvelteKitIts starter project loads a link's data on hover, or on touch on a phone.It never preloads.
AstroLinks you mark, or every link if you ask. On hover, unless you pick another strategy.It waits for a tap instead.
quicklinkLinks on screen, once the browser is idle.It doesn't prefetch, and not on 2G either.
Chrome's eager rule, on a phoneWhen 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.
Real-life analogyA bus ticket for every route

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:

Hit rate and wastePop out in the code editor (opens in a new tab)JavaScript
// 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 wasted and predicted: hit rate 50%, 1167 bytes wasted.
The tea pages Chrome fetched before Asha's tap, for each way of guessing, and which one she opened. Viewport: Mint tea, Green tea, Chamomile, Black tea, Jasmine, Oolong, 7.0 kB; she opened Mint tea. Prerender: Mint tea, Green tea, Chamomile, Black tea, Jasmine, Oolong, 450.9 kB; she opened Mint tea. Hover: Mint tea, 1.2 kB; she opened Mint tea. Predicted: Mint tea, Green tea, 2.3 kB; she opened Mint tea. Wrong guess: Mint tea, Green tea, 2.3 kB; she opened none of them.pages Chrome fetched before the tapViewport7.0 kBMint teaGreen teaChamomileBlack teaJasmineOolongPrerender450.9 kBMint teaGreen teaChamomileBlack teaJasmineOolongeach with its photoHover1.2 kBMint teaPredicted2.3 kBMint teaGreen teaWrong guess2.3 kBMint teaGreen teaAsha opened Jasmine insteadopenednever opened
Solid cards: pages Asha opened. Dashed cards: pages fetched for nothing. Under each name, the bytes Chrome fetched before the tap.

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 same guesses, prefetched or prerenderedPop out in the code editor (opens in a new tab)JavaScript
// 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.

What each guess cost before Asha's tap
How Ravi guessedFetched before the tapBytes before the tapBytes for teas she never openedPhoto 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:

Playground: a day of guesses
How the playground countsJavaScript
// 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;
One dayWorked out
Viewport: pages fetched ahead6,000
Viewport: wasted5.8 MB
Viewport: pages built for nothing5,000
Viewport, prerender: pages fetched ahead6,000
Viewport, prerender: wasted346.9 MB
Viewport, prerender: pages built for nothing5,000
Hover, 700 ms rest: pages fetched ahead1,000
Hover, 700 ms rest: wasted0 MB
Hover, 700 ms rest: pages built for nothing0
Predicted: pages fetched ahead2,000
Predicted: wasted1.2 MB
Predicted: pages built for nothing1,000
Try it yourself
1,000 visits, each like Asha's

Each visit fetches what Asha's did. The waste is the bytes and the server builds for teas nobody on that visit opened.

Per visit, from the recording in Chrome 157: the pages fetched before the tap, and the bytes and pages for teas Asha never opened. Real visitors open different teas, so treat it as a rough guide.

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: on to its requests. A server doesn't have to ask for it.
  • navigator.connection.saveData, which is true for the page's own scripts.
Real-life analogyA 'No flyers, please' sticker

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
Android's Data Saver setting, on Asha's phone, shows up in three places. Chrome sends Save-Data: on with its requests. navigator.connection.saveData is true for the page's scripts. And Chrome skips every speculation rule.Asha's phoneData Saver onSave-Data: ona header the server seessaveData: truewhat the page's script readsno speculationChrome skips every rule
One setting on the phone. Ravi's server reads the header, his scripts read 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:

Three lists, with DevTools saying save dataPop out in the code editor (opens in a new tab)JavaScript
// 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 0 and Script checks saveData: 0 and 0.

Here is the check in Ravi's script. Only line 4 changed:

The viewport script, for visitors who don't save dataJavaScript
// 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:

The server leaves the rule outJavaScript
// 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 met Vary: 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?

Playground: does your browser ask to save data?
What this lab readsJavaScript
// 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;
This browserreading
navigator.connection…
saveData…
effectiveType…
Try it yourself
Your browser

Reading navigator.connection.

This reads your own browser, on this page. Turn on Data Saver on an Android phone, open this page in Chrome, and read it again.

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:

Which guess for which link?
  • 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
Try it yourself
0 of 8 correct

Sort each link by how Ravi should prefetch it.

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

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.

Exercise 1 · Warm-upA 200 px margin

With a 200 px margin around the screen, Ravi's list would fetch all eight teas. What does this print?

Starter codePop out in the code editor (opens in a new tab)JavaScript
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)}%`);

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

    Exercise 2 · Warm-upThe time a 300 ms rest saved

    What does this print?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const noPrefetching = 712.8;
    const rest300 = 610.7;
    console.log(`Resting 300 ms saved ${(noPrefetching - rest300).toFixed(1)} ms.`);

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

      Exercise 3 · PracticeJasmine, the normal way

      In the playground with seven ways to guess, pick the wrong guess. How many ms after the tap did Jasmine's HTML start arriving?

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

        Exercise 4 · PracticeSkip visitors who save data

        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?

        Starter codeJavaScript
        // 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 });
        }

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

          Exercise 5 · ChallengeRavi's list in DevTools

          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?

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

            Exercise 6 · ChallengeData Saver on Asha's phone

            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?

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

              Check your understanding

              For each question, ask what was fetched before the tap, and who paid for it.

              The prefetching strategies quiz · 7 questionsScore: first tries count
              1. Question 1 of 7What does the second 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 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.

              2. 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.

              3. 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.

              4. 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.

              5. 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.

              6. 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.

              7. 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 scripts navigator.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:

              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.

              CompleteFrontend Clear concepts. Working examples.