Project: instant navigations
Make a multi-page store feel instant: fix what keeps pages out of the back/forward cache, add Speculation Rules and a view transition, and measure each kind.
- 01Find and fix back/forward cache blockersRead DevTools' test and notRestoredReasons from real trips, fix one blocker at a time, and check every trip is restored.
- 02Fetch or build the next page before the clickPrefetch on hover with moderate Speculation Rules, prerender the likely next page, and check deliveryType and activationStart.
- 03Add a transition, and measure everythingAdd a cross-document view transition, measure what it costs, and split the field's LCP by navigation type.
Every click starts from white
Asha is buying tea at Leaf and Kettle, on her laptop. She clicks Teas and waits while the tea list builds. She clicks Mint tea and waits again. She opens the brewing guide and adds the tea to her cart. Then she presses Back to look at the list once more. The Mint tea page stays on screen for almost half a second. Then the list loads again, from the start.
Each page on its own loads fast now. Lesson 45.1 saw to that. So why does moving around the store still feel slow? And can Ravi make each step feel instant?
Here is where this project ends. These are the times of Asha's trip in the lab, before and after:
1// Asha's trip in the lab: ms from her click, or from Back or Forward,2// until the page's largest content was on screen. The middle of 5 trips.3const before = { teas: 637, mint: 628.3, backToTeas: 463.9, forwardToTeas: 476.9 };4const after = { teas: 238.6, mint: 47.6, backToTeas: 30.9, forwardToTeas: 27.1 };5 6for (const step of Object.keys(before)) {7 console.log(`${step}: ${before[step]} ms, now ${after[step]} ms`);8}- Lines 1 and 2 are comments. Each time starts when Asha clicks, or presses Back or Forward. It ends when the page's largest content is on screen: the page's LCP, counted from the press. A millisecond (ms) is a thousandth of a second.
- Line 3 holds four times from before the project. Line 4 holds the same four after it.
- Lines 6 to 8 print one line for each step. The first is
teas: 637 ms, now 238.6 ms.
Three of the four now take under 50 ms. A screen draws a new frame every 16.7 ms, so that's three frames or fewer. Why it matters: a page that arrives this fast feels like part of the page before it.
Here is Asha's click on Mint tea, half a second later, before the project and after it:
Each step of the project does one job. A good library helper does all of them:
You read at a library desk. You put a book down to look something up. A good helper leaves it open at your page, so you can carry on. When you reach for the next book in a series, the helper fetches it. And the book nearly every reader wants next is already on your desk.
- In real life: Your book, left open at your page
- In web performance: The back/forward cache: Back shows the page Chrome kept
- In real life: Fetching the book you reach for
- In web performance: A prefetch, when the pointer rests on a link
- In real life: The book most readers want next, already on the desk
- In web performance: A prerender of the likely next page
- In real life: Opening the new book gently
- In web performance: A view transition between the pages
A navigation feels instant when the browser has nothing left to build after the press. Keep pages for Back and Forward, fetch or build the next page before the click, and soften the change. Then measure each kind of navigation on its own, because each one arrives a different way.
The project has four steps:
- Step 1: let Back and Forward restore pages, by fixing what keeps them out of the back/forward cache.
- Step 2: fetch the next page before the click, with Speculation Rules.
- Step 3: fade from one page to the next, with a view transition.
- Step 4: measure each kind of navigation, in the lab and in the field.
Build each step on your own copy of the store. The course's files for each step are published. Keep each step's files in one folder, and save its home.html as index.html. Then run node serve.mjs in that folder. It serves the store with the headers each page needs.
- Before (serve.mjs): the store before the project, with its scripts, photos and serve.mjs in the same folder.
- Step 1: the cache (serve.mjs): after step 1: every trip back and forward restored.
- Step 2: Speculation Rules (serve.mjs): after step 2: the rules in every page's head.
- Step 3: view transitions (serve.mjs): after step 3: the fade between pages.
How the course recorded it
- The store: each version ran its own
serve.mjs, at a made-up address, https://shop.example. A small HTTPS server in front stood in for the network. Each answer waited 165 ms, like DevTools' Fast 4G, and each page waited 250 ms more, like a server building it. - The lab: Chrome for Testing 157.0.8103.52, in a window 800 pixels wide, with the CPU 4× slower. Asha's trip ran 5 times at each version, the versions taking turns. The mouse rested on each link for at least 300 ms before it pressed. Back and Forward went through DevTools' protocol, which runs the same code as Chrome's buttons.
- The times: from the press to the largest content on screen, read from Chrome's trace. After a restore, the course waited two frames after the page came back, the way the web-vitals library counts it.
- The field: 36 computers like lesson 13.1's, each on its own network. Each one made a shopping trip of its own twice: before the project and after it. Every page view sent its numbers to lesson 45.2's collector.
Step 1: let Back and Forward restore the page
When Asha leaves a page, Chrome can keep the whole page in memory, paused. If she presses Back, Chrome shows the kept page instead of loading it. That's the back/forward cache, or bfcache, from lesson 33.1. On Ravi's store, it never worked. Asha's trip goes back twice and forward twice. In 5 trips, that's 20 chances, and not one page came back from the cache.
So the first job is to find out why. Chrome can tell you in two places.
Ask DevTools
Open DevTools' Application panel. Under Background services, pick Back/forward cache, and press Test back/forward cache. DevTools leaves the page for chrome://terms, a page on another site, and then comes back. The course ran the same test on the home page, the tea list and the Mint tea page. All three gave one reason, under Actionable: "The page has an unload handler in the main frame".
That's Ravi's old analytics script. It sends how long each visit lasted from an unload listener. Lesson 33.1 showed the problem. The standard runs unload only for a page that won't be kept. So a page that listens for it gets thrown away. Chrome's guide says unload listeners no longer run by default, and lesson 33.1 showed why a fresh Chrome, like the lab's, still runs them. Firefox keeps such pages out of its cache. Either way, unload is the wrong place for Ravi's report.
Ask the page itself
DevTools' test leaves and comes back at once. A real trip is different: Asha adds tea to her cart while the old page waits. So the page can also ask why it wasn't restored. Its navigation entry, from lesson 5.1, has a field for it, notRestoredReasons:
// After Back or Forward: why wasn't this page restored?
const entry = performance.getEntriesByType("navigation")[0];
if (entry.type === "back_forward" && entry.notRestoredReasons) {
console.log(entry.notRestoredReasons.reasons.map((item) => item.reason));
}- Line 2 gets the page's navigation entry.
- Line 3 checks that this was a trip back or forward, with reasons. It's
nullon a normal visit, and when nothing kept the page out. - Line 4 prints the name of each reason.
On Asha's trip back to the tea list, it printed only ["masked"]. Masked means "there was a reason, but I won't name it". DevTools' protocol named two for the same trip: the unload handler, and one the panel calls "Internal error". Why it matters: a report from the field can be vague. Make the same trip in DevTools to see the names.
The unload listener also hid other problems. A page thrown away as Asha left it never met the trouble that came later, like a cookie change or a message. To find the rest, Ravi has to fix one, make the trip again, and read again.
After a storm, trees lie across a forest road. From your car, you see only the first one. You clear it, drive on, and find the next. You only know the road is open when you reach the end.
- In real life: The first tree, the only one you can see
- In web performance: The unload listener, which kept every page out
- In real life: The trees behind it
- In web performance: The blockers it hid
- In real life: Clearing one tree and driving on
- In web performance: Fixing one blocker, then making the trip again
- In real life: Reaching the end of the road
- In web performance: Every trip back and forward restored
Fix 1: report on pagehide
1// analytics.js: counts each page view, and how long the visitor stayed.2let started = performance.now();3const send = (data) => navigator.sendBeacon("/visit", JSON.stringify({ page: location.pathname, ...data }));4send({});5addEventListener("pagehide", () => send({ stayed: Math.round(performance.now() - started) }));6addEventListener("pageshow", (event) => {7 if (!event.persisted) return;8 started = performance.now();9 send({ restored: true });10});- Line 4 counts the page view.
- Line 5 sends the time on the page from
pagehide. It used to sayunload.pagehidefires whenever the page is left, kept or not, so the page can still be kept. - Lines 6 to 10 count a page that comes back from the cache as a new view. A restored page doesn't run its scripts again, so without them, Ravi's numbers would miss every restore.
Ravi also sends one more header with his pages, from his server:
1const PAGE = { "cache-control": "no-cache", "permissions-policy": "unload=()" };2const HEADERS = {3 "/styles.css": { "cache-control": "no-cache" },Line 1 adds Permissions-Policy: unload=(), from lesson 33.1. It allows unload listeners for no one, so no script can add one again. Then Ravi makes the trip again. Now the page names its reasons. Pick each fix in the playground to read what Chrome said, trip by trip:
Before- Back to the tea list
{ "src": null, "id": null, "url": "/teas.html", "name": null, "reasons": [{ "reason": "masked" }], "children": [] }DevTools:BrowsingInstanceNotSwapped(Not actionable): Internal error;UnloadHandlerExistsInMainFrame(Actionable): The page has an unload handler in the main frame - Back to home
{ "src": null, "id": null, "url": "/", "name": null, "reasons": [{ "reason": "masked" }], "children": [] }DevTools:BrowsingInstanceNotSwapped(Not actionable): Internal error;UnloadHandlerExistsInMainFrame(Actionable): The page has an unload handler in the main frame - Forward to the tea list
{ "src": null, "id": null, "url": "/teas.html", "name": null, "reasons": [{ "reason": "masked" }, { "reason": "non-trivial-browsing-context-group" }], "children": [] }DevTools:RelatedActiveContentsExist(Not actionable): The page was opened using 'window.open()' and another tab has a reference to it, or the page opened a window;BrowsingInstanceNotSwapped(Not actionable): Internal error - Forward to Mint tea
{ "src": null, "id": null, "url": "/mint-tea.html", "name": null, "reasons": [{ "reason": "masked" }, { "reason": "non-trivial-browsing-context-group" }], "children": [] }DevTools:RelatedActiveContentsExist(Not actionable): The page was opened using 'window.open()' and another tab has a reference to it, or the page opened a window;BrowsingInstanceNotSwapped(Not actionable): Internal error
For each trip back or forward: the notRestoredReasons object the shown page read, and the reasons DevTools' protocol named for the same trip. A restored page gets no new entry, so it has nothing to read.
Fix 2: no-cache, not no-store
After fix 1, Back to the tea list gave two reasons. One was response-cache-control-no-store. Here is Ravi's server before the project:
1const PAGE = { "cache-control": "no-cache" };2const HEADERS = {3 // The tea list shows what's in stock, so it must never be stale.4 "/teas.html": { "cache-control": "no-store" },5 "/styles.css": { "cache-control": "no-cache" },Line 4 sends the tea list with Cache-Control: no-store, so it's never stale. Lesson 33.1 showed what that does. Chrome keeps a no-store page, but throws it out if a cookie changes while it waits. Asha's Add to cart changes the cart cookie.
no-store kept the list out of the HTTP cache too. So before the project, Back to the tea list waited for the server: 463.9 ms. Back to home came from the HTTP cache in 44.3 ms. The fix is to delete line 4. Then the list gets the same headers as every other page. Its no-cache means a normal visit still checks with the server, and Back can keep the page. It also gets the Permissions-Policy from fix 1, which line 4 had left out.
Fix 3: close the channel while the page waits
Now two trips said broadcastchannel-message. Ravi's app.js keeps the cart count the same in every open tab. It uses a BroadcastChannel: a named channel that every page of the site can send messages on.
const channel = new BroadcastChannel("cart");
channel.onmessage = show;
show();Line 1 opens the channel, called "cart". Line 2 updates the count whenever a message comes. When Asha taps Add to cart, the Mint tea page posts "added". The home page and the tea list still had the channel open while they waited. A frozen page can't hear a message, so Chrome threw them out.
1let channel;2const listen = () => {3 channel = new BroadcastChannel("cart");4 channel.onmessage = show;5};6listen();7show();8addEventListener("pagehide", () => channel.close());9addEventListener("pageshow", (event) => {10 if (!event.persisted) return;11 listen();12 show();13});- Lines 1 to 6 open the channel, as before, through a small
listen()function. Line 7 shows the count. - Line 8 closes it on
pagehide. A closed channel gets no messages, so the page can wait in the cache. - Lines 9 to 13 run when the page comes back. Line 11 opens the channel again. Line 12 updates the count, because Asha may have added tea while the page waited, and the page missed the message.
Fix 4: open the guide with noopener
One trip was still out: Forward to Mint tea, with non-trivial-browsing-context-group. The Brewing guide button opens a small window with window.open(). A window opened that way can reach back to the page that opened it, through window.opener. So the two pages are tied together, and Chrome won't keep one of them in the cache while the other is open. DevTools says it plainly: "the page opened a window".
1document.querySelector("#guide")?.addEventListener("click", () => {2 window.open("brewing.html", "guide", "popup,width=420,height=560,noopener");3});Line 2 adds noopener. The guide still opens in its small window, but with no way back to the Mint tea page. Here are the four blockers together:
notRestoredReasons gave on a real trip back or forward. For the unload listener it only said masked, so DevTools named it.After the fourth fix, all 20 trips back and forward came back from the cache. Back to the tea list took 28.0 ms, counted the web-vitals way. The list's first frame was on screen 7.9 ms after Back. Why it matters: Back and Forward are a big share of all navigations. Here they were 39% of the field's page views.
Step 2: fetch the next page before the click
Back and Forward are instant now. Clicking a link isn't. Home to the tea list still took 651.7 ms, and the tea list to Mint tea 669.1 ms. Most of that is waiting for the server.
Speculation Rules, from lesson 33.2, let a page tell Chrome which pages to get ready early. A prefetch fetches a page's HTML. A prerender builds the whole page, scripts and all, in a hidden tab. Ravi puts rules in every page's head. On the tea list, they have one more line:
1<script type="speculationrules">2{3 "prefetch": [{ "where": { "href_matches": "/*" }, "eagerness": "moderate" }],4 "prerender": [{ "urls": ["/mint-tea.html"] }]5}6</script>- Lines 1 and 6 hold a
speculationrulesscript. The browser reads JSON there, not JavaScript. - Line 3 is a prefetch rule.
wherepicks every link whose address matches/*: any page of the store.moderatesays when. On a computer, Chrome starts once the pointer has rested on a link for 200 ms. - Line 4 is a prerender rule with a list of addresses: the Mint tea page, the store's best seller. A list rule with no eagerness starts at once.
A café cook watches the room. When a diner's finger rests on a dish in the menu, she takes out its ingredients. And the dish nearly everyone orders after lunch, she starts before anyone asks. When the order comes, it's on the plate in moments.
- In real life: A diner's finger resting on a dish in the menu
- In web performance: The pointer resting on a link for 200 ms
- In real life: Taking out that dish's ingredients
- In web performance: A prefetch: the page's HTML, fetched
- In real life: The dish nearly everyone orders, started early
- In web performance: A prerender of the Mint tea page
- In real life: Serving it the moment it's ordered
- In web performance: Showing the prerendered page on the click
Moderate has limits, so hovering doesn't fetch the whole store. In Chrome 157.0.8103.52's code, a page keeps at most two moderate prefetches. A third pushes out the oldest.
What Asha's trip measured
Chrome asked for the tea list 404.1 ms before Asha clicked, once the pointer had rested on Teas. When she clicked, the answer was nearly back. The first byte of its HTML came 11.7 ms after the click, instead of 422.5. Its LCP came at 239.2 ms instead of 651.7: its style sheet still came from the network, after the click.
The Mint tea page did even better. Chrome built it while Asha read the list:
activationStart, 3,451.4 ms, is the time from its start to the click, on its own clock.The page can tell how it arrived. Here is what its entry said, and what web-vitals reported:
1// The Mint tea page Asha saw: its navigation entry, and what web-vitals reported.2const entry = { deliveryType: "navigational-prefetch", activationStart: 3451.4 };3const webVitals = { navigationType: "prerender", lcp: 33 };4 5console.log(`Delivered by ${entry.deliveryType}, built ${entry.activationStart} ms before it was shown.`);6console.log(`web-vitals: ${webVitals.navigationType}, LCP ${webVitals.lcp} ms.`);- Line 2 holds two fields of the navigation entry.
deliveryTypeis"navigational-prefetch": the HTML came from a fetch made ahead of time.activationStartis when the hidden page was shown, on its own clock. - Line 3 is what web-vitals reported. It counts LCP from
activationStart, so the number is the time Asha waited. - Lines 5 and 6 print
Delivered by navigational-prefetch, built 3451.4 ms before it was shown.andweb-vitals: prerender, LCP 33 ms.
Why it matters: a prerendered page shows up in about two frames. But it costs work every time, used or not. Prerender only the page most visitors open next, and let hover fetch the rest.
One side effect to fix
A prerendered page runs its scripts while it's hidden. Ravi's analytics.js would count a view that Asha might never see. Lesson 33.2 showed the fix:
1const shown = () => {2 started = performance.now();3 send({});4 addEventListener("pagehide", () => send({ stayed: Math.round(performance.now() - started) }));5};6// A prerendered page starts counting when the visitor sees it, not while Chrome builds it.7if (document.prerendering) document.addEventListener("prerenderingchange", shown, { once: true });8else shown();- Lines 1 to 5 make a
shown()function. It starts the clock, counts the view, and listens forpagehide. - Line 7 waits while the page is prerendering.
prerenderingchangefires when Asha clicks and the page is shown. - Line 8 starts at once on a normal visit.
In the recording, every page-view beacon came from a page Asha had seen.
Step 3: fade from one page to the next
The pages arrive fast now, but they still swap with a hard cut. Ravi wants the old page to fade into the new one. That's a cross-document view transition, from lesson 32.3. Both pages opt in with CSS. Chrome takes a picture of the old page, then fades it into the new one, over a quarter of a second.
Ravi's first try puts the opt-in at the end of styles.css, which every page loads:
@media (prefers-reduced-motion: no-preference) {
@view-transition {
navigation: auto;
}
}- Lines 1 and 5 keep the fade for visitors who haven't asked their system for less motion.
- Lines 2 to 4 are the opt-in.
navigation: autoasks for a transition when the visitor moves between two pages that both opt in.
Then he measured. Back and Forward faded, in all 5 trips. So did the prerendered Mint tea page. But the click from home to the tea list didn't fade, in any of the 5 trips. Chrome's console said why:
InvalidStateError: Transition was aborted because of invalid state. ViewTransition opt-in disabled"Opt-in disabled" means the new page didn't ask for a transition in time. In Chrome 157.0.8103.52's code, a new page reads its opt-in when the HTML reaches its <body> tag. styles.css comes in a request of its own, after the HTML. On a link click, it hadn't arrived yet. It's like a sign on a shop door that goes up after the first customer has already looked.
So Ravi moves the opt-in into each page's head, where it arrives with the HTML:
1<style>2 @media (prefers-reduced-motion: no-preference) {3 @view-transition { navigation: auto; }4 }5</style>Line 3 is the same rule, and lines 1 and 5 hold it in a <style> element. Now every navigation in every trip faded: 30 of 30. Why it matters: test each kind of navigation after you add a transition. Back and Forward working doesn't mean a link does.
What the fade costs
A lift stops at your floor, and its doors slide open. The floor was there the moment the lift stopped. The doors only make arriving feel smooth. If they took five seconds, you would stand and wait at a floor you had already reached.
- In real life: The lift stopping at your floor
- In web performance: The new page ready: its LCP
- In real life: The doors sliding open
- In web performance: The fade, a quarter of a second
- In real life: Doors that take five seconds
- In web performance: A long transition that keeps the visitor waiting
The course made Asha's trip with the fade and without it. Here is the click on Mint tea:
1// The middle of five trips, in ms from the click on Mint tea.2const without = { lcp: 38.1 };3const withFade = { lcp: 47.6, fadeEnded: 304 };4 5console.log(`LCP: ${without.lcp} ms, then ${withFade.lcp} ms with the fade`);6console.log(`The fade ended at ${withFade.fadeEnded} ms`);- Line 2 is the LCP without the fade, in step 2. Line 3 is the LCP with it, and when the fade ended.
- Lines 5 and 6 print
LCP: 38.1 ms, then 47.6 ms with the fadeandThe fade ended at 304 ms.
The fade added 9.5 ms to the LCP, while Chrome took the old page's picture. Then the fade ran until 304.0 ms. LCP didn't count the fade: Chrome reported it as the fade began. On Back and Forward, the fade ended 275 to 292 ms after the press.
Why it matters: the fade costs little time to the page, but Asha watches it for a quarter of a second on every navigation. Keep it short. And keep it for people who haven't asked for less motion, as lines 2 and 4 of the <style> element do.
Step 4: measure each kind of navigation
Every step changed one kind of navigation. So measure each kind on its own. Start in the lab. Pick a checkpoint to see Asha's whole trip there:
Before- Home to the tea list637.0 msLoaded from the network.
- The tea list to Mint tea628.3 msLoaded from the network.
- Back to the tea list463.9 msLoaded from the network.
- Back to home44.3 msLoaded again, from the HTTP cache.
- Forward to the tea list476.9 msLoaded from the network.
- Forward to Mint tea42.4 msLoaded again, from the HTTP cache.
Each row is one navigation of the trip: how the page arrived, and the time from the press to its largest content on screen. The faint bar is the same navigation before the project.
Before the project, every navigation loaded a page. By the end, Back and Forward restored, the Mint tea page was prerendered, and the tea list came from a prefetch. The tea list is the slowest one left: it still waits for its style sheet.
In the field
The lab has one visitor and one trip. The field has many. Ravi already sends LCP from every visit, with lesson 45.2's rum.js. It needs two changes for this project. First, each beacon says how the page arrived:
1onLCP(({ value, navigationType, attribution: a }) => {2 beacon.nav = navigationType;3 beacon.lcp = { value, element: a.target ?? null, parts: [a.timeToFirstByte, a.resourceLoadDelay, a.resourceLoadDuration, a.elementRenderDelay] };4});- Line 1 takes
navigationTypefrom web-vitals' report, along with the LCP. - Line 2 keeps it in the beacon. web-vitals says
navigate,back-forwardwhen Back loaded the page again,back-forward-cacheafter a restore, andprerender.
Second, a restored page is a new page view, so it gets a new beacon:
1let sent = false;2// A page restored from the back/forward cache is a new page view: start a new beacon.3addEventListener("pageshow", (event) => {4 if (!event.persisted) return;5 beacon = start();6 sent = false;7});- Line 1 is lesson 45.2's flag: send once. A restored page keeps it, so without the next lines it would never send again.
- Lines 3 to 7 run when the page comes back. Line 5 starts a fresh beacon, and line 6 lets it be sent. web-vitals reports the restored page's numbers after that.
The collector learns the store's pages, and checks the new field like the others:
const NAVIGATIONS = ["navigate", "reload", "back-forward", "back-forward-cache", "prerender", "restore"];
// In clean(), next to the other fields:
nav: NAVIGATIONS.includes(body.nav) ? body.nav : "unknown",Line 1 lists the types the collector accepts. Line 4 keeps a beacon's type, or "unknown". Then a short script splits the page views by type:
1// by-navigation.mjs: page views and LCP p75 for each way a page arrived. Run it with: node by-navigation.mjs2import { readFileSync } from "node:fs";3 4const FILE = process.argv[2] ?? "beacons.jsonl";5const beacons = readFileSync(FILE, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line));6const p75 = (values) => values.toSorted((a, b) => a - b)[Math.ceil(values.length * 0.75) - 1];7 8const withLcp = beacons.filter((beacon) => beacon.lcp);9const groups = Object.groupBy(withLcp, (beacon) => beacon.nav);10for (const [nav, views] of Object.entries(groups).sort((a, b) => b[1].length - a[1].length)) {11 const share = Math.round((views.length / withLcp.length) * 100);12 console.log(`${nav}: ${views.length} page views (${share}%), LCP p75 ${Math.round(p75(views.map((view) => view.lcp.value)))} ms`);13}- Lines 4 and 5 read one beacon per line from the file.
- Line 6 is the p75 from lesson 45.2: the value three quarters of the way up.
- Line 9 groups the page views that have an LCP by their type.
Object.groupBy()makes one list per type. - Lines 10 to 13 print each type, the biggest first: how many page views, their share, and their LCP p75.
The course sent 36 visitors through the store, each one before the project and after it. Here is what the script printed for each:
navigate: 140 page views (61%), LCP p75 412 ms
back-forward: 90 page views (39%), LCP p75 328 msnavigate: 110 page views (48%), LCP p75 384 ms
back-forward-cache: 90 page views (39%), LCP p75 20 ms
prerender: 30 page views (13%), LCP p75 38 msA post office wants faster parcels. It times next-day parcels, standard parcels, and parcels people collect at the counter. If it put all three into one average, more counter pickups would make the average better, even if no van got faster.
- In real life: Each delivery service
- In web performance: Each navigation type
- In real life: Parcels collected at the counter
- In web performance: Pages restored from the back/forward cache
- In real life: Parcels sent before they were ordered
- In web performance: Prerendered pages
- In real life: One average for all parcels
- In web performance: One LCP p75 for every page view
Before, every trip back loaded a page again: a hit rate of 0%. After, 100% of trips back and forward were restored, with an LCP p75 of 20 ms. The 30 prerendered page views had an LCP p75 of 38 ms.
Look at navigate too: the pages that loaded, prefetched or not. Its p75 went from 412 to 384 ms. All page views together went from 384 to 320 ms. Most of that drop came from the restores and the prerenders, which turned slow loads into quick ones. Why it matters: split by type, as lesson 12.5 showed, and you can see which navigations really got faster.
Which step makes this trip instant?
Each card is one navigation on the finished store. Sort it by what made it fast in the recording, or by nothing:
- Back to the tea list, after Add to cart
- Forward to the Mint tea page, with the brewing guide still open
- Clicking Mint tea on the tea list
- Clicking Teas, after resting the pointer on it
- Clicking Mint tea on the home page, after resting the pointer on it
- Typing the store's address into a new tab
Sort each navigation by what made it fast on the finished store.
Read the table across: each row is one way a page arrives, and how to tell.
| How the page arrived | What the page can read | What web-vitals says |
|---|---|---|
| Loaded from the network. | Its entry's type is navigate, and deliveryType is empty. | navigate. |
| Loaded from a prefetch. | Its entry's deliveryType is navigational-prefetch. | navigate, because the page still loaded. |
| Prerendered, then shown. | Its entry's activationStart is more than 0. | prerender, with LCP counted from activationStart. |
| Loaded again on Back or Forward. | Its entry's type is back_forward, and notRestoredReasons says why. | back-forward. |
| Restored from the back/forward cache. | pageshow fires with persisted set to true. The entry is the old one. | back-forward-cache, with LCP two frames after pageshow. |
Common mix-ups
- "DevTools' test finds every blocker." No. It found only the unload listener. The cookie change, the channel's message and the popup happen on real trips.
- "notRestoredReasons names every blocker at once." No. It said only
maskedfor the unload listener, and a page thrown away as it was left never met the later blockers. Fix one, then make the trip again. - "no-cache keeps a page out of the back/forward cache, like no-store." No. With
no-cache, the tea list was restored on every trip. - "Moderate prefetches every link on the page." No. It waits for the pointer to rest on a link for 200 ms, and keeps two prefetches at most.
- "An opt-in in the shared stylesheet is enough for every navigation." No. The link clicks skipped the fade, because
styles.cssarrived after the page's body began. - "If the overall LCP p75 drops, every navigation got faster." No. Restores and prerenders pull it down on their own. Split the page views by navigation type.
Practice exercises
Answer first, then use the hints. Two use the playgrounds, one uses DevTools on a published page, and one uses Chrome's docs.
After fix 2, the course counted the trips back and forward in five trips. What does it print?
// After fix 2, in the lab: every trip back and forward of five trips.
const trips = 20;
const restored = 5;
console.log(`${Math.round((restored / trips) * 100)}% restored`);25% restored. After fix 2, only Forward to the tea list came back from the cache: the channel's message kept out both trips back, and the popup kept out Forward to Mint tea.
This is how web-vitals names a page view, shortened. What does the last line print?
// How web-vitals names a page view, shortened from its initMetric.ts.
function navigationType(entry, restored) {
if (restored) return "back-forward-cache";
if (entry.activationStart > 0) return "prerender";
return entry.type.replace(/_/g, "-");
}
console.log(navigationType({ type: "navigate", activationStart: 3451.4 }, false));prerender. A page with an activationStart was prerendered, so web-vitals counts its LCP from that moment.
At Step 3, when did the fade end on Back to home, in ms?
274.8 ms. The home page was back after 26.7 ms; the rest is the fade.
After fix 1, which reason did DevTools' protocol give, under Actionable, on Back to the tea list?
CacheControlNoStoreCookieModified. It names the cause more exactly than the page's response-cache-control-no-store: a cookie changed.
Open the store after step 2 in Chrome. What does the tea list request's Sec-Purpose header say?
prefetch. Chrome marks every request it makes ahead of time, so a server can tell it from a visit.
Read Prerender pages in Chrome. Which eagerness waits until the visitor presses the link?
conservative. It starts on pointer down, so it wastes almost nothing but saves only the time between pressing and letting go.
Check your understanding
For each question, ask which kind of navigation it is about, and how that page arrived.
Question 1 of 7Before the first fix, Back to the tea list gave only
maskedin notRestoredReasons. What does that mean?Choose an answer to see the explanation.
Question 2 of 7The tea list must never be stale. Which header keeps it fresh and still lets Back restore it?
Choose an answer to see the explanation.
Question 3 of 7Why does app.js close its BroadcastChannel on pagehide?
Choose an answer to see the explanation.
Question 4 of 7A prefetch rule says
"eagerness": "moderate". When does Chrome on a computer fetch a link?Choose an answer to see the explanation.
Question 5 of 7web-vitals reported a short LCP for the prerendered Mint tea page, though Chrome began building it seconds before the click. Why?
Choose an answer to see the explanation.
Question 6 of 7The first try at the fade put the opt-in in styles.css. Why did the link clicks skip the fade?
Choose an answer to see the explanation.
Question 7 of 7What does this print?
Read the code, then predictPop out in the code editor (opens in a new tab)JavaScriptconst p75 = (values) => values.toSorted((a, b) => a - b)[Math.ceil(values.length * 0.75) - 1]; const loaded = [380, 400, 420, 440]; const restored = [20, 22, 24, 26]; console.log(p75(loaded), p75([...loaded, ...restored]));Choose an answer to see the explanation.
Key takeaways
- Find back/forward cache blockers with DevTools' test and with notRestoredReasons from real trips. Fix one, then trip again.
- Use pagehide, not unload. Prefer no-cache to no-store. Close channels on pagehide. Open windows with noopener.
- Prefetch on hover with moderate rules, and prerender only the page most visitors open next.
- Put the view transition opt-in in each page's head, and check that every kind of navigation fades.
- Send the navigation type with every beacon, start a new beacon after a restore, and read LCP for each type.
Remember the one-liner.
Keep the last page, get the next one ready, soften the change, and measure each kind of navigation on its own.
Sources
The facts on this page come from these docs, standards and source files:
- Back/forward cache, web.dev.
- BackForwardCacheView.ts: the Test back/forward cache button, Chrome DevTools source.
- BackForwardCacheStrings.ts: the panel's names for each reason, Chrome DevTools source.
- Back/forward cache notRestoredReasons API, Chrome for Developers.
- HTML Standard: NotRestoredReasons, WHATWG.
- back_forward_cache_can_store_document_result.cc, lines 508 to 640: Chrome's reason names, Chromium source.
- back_forward_cache_impl.cc, lines 1033 to 1057: pages with another window in their group, Chromium source.
- Deprecating the unload event, Chrome for Developers.
- Back/forward cache for Cache-Control: no-store pages, Chrome for Developers.
- BroadcastChannel, MDN.
- Window: open() method, noopener, MDN.
- HTML Standard: Speculative loading, WHATWG.
- Prerender pages in Chrome for instant page navigations, Chrome for Developers.
- anchor_element_interaction_tracker.h, lines 113 and 114: moderate's 200 ms, Chromium source.
- prefetch_features.cc, lines 102 to 104: two moderate prefetches per page, Chromium source.
- prefetch_document_manager.cc, lines 340 to 385: the oldest goes first, Chromium source.
- Prerendering Revamped: activationStart, WICG.
- PerformanceResourceTiming: deliveryType, MDN.
- Cross-document view transitions, Chrome for Developers.
- CSS View Transitions Module Level 2, W3C.
- view_transition_commit_deferring_condition.cc: which navigations get a transition, Chromium source.
- web-vitals: initMetric.ts (6.2.3), the navigation types, Google Chrome on GitHub.
- web-vitals: onLCP.ts (6.2.3), LCP after a prerender and a restore, Google Chrome on GitHub.
The reader's field files are published too:
- rum.js: lesson 45.2's RUM script, with the navigation type and a new beacon after a restore.
- collector.mjs: the collector, with the store's pages and the navigation types.
- by-navigation.mjs: page views and LCP p75 for each navigation type.
- beacons-before.jsonl: the field's page views before the project.
- beacons-after-view-transitions.jsonl: the same visitors' page views after it.
Coming next: Project: an image pipeline. You'll build a pipeline that turns the store's photos into the right sizes and formats.