completefrontend
Open lab My progress
THE WEB PERFORMANCE FIELD GUIDE

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.

By the end, you can
  • 01
    Find 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.
  • 02
    Fetch or build the next page before the clickPrefetch on hover with moderate Speculation Rules, prerender the likely next page, and check deliveryType and activationStart.
  • 03
    Add 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:

Asha's trip, before and after the projectPop out in the code editor (opens in a new tab)JavaScript
// Asha's trip in the lab: ms from her click, or from Back or Forward,// until the page's largest content was on screen. The middle of 5 trips.const before = { teas: 637, mint: 628.3, backToTeas: 463.9, forwardToTeas: 476.9 };const after = { teas: 238.6, mint: 47.6, backToTeas: 30.9, forwardToTeas: 27.1 }; for (const step of Object.keys(before)) {  console.log(`${step}: ${before[step]} ms, now ${after[step]} ms`);}
  • 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:

Two real frames, 500 ms after Asha clicked Mint tea on the tea list. Before the project, the screen still shows the tea list. After it, the Mint tea page is there. Below, each navigation of her trip, from the press to the largest content on screen: Home to the tea list, 637.0 ms before and 238.6 ms after; The tea list to Mint tea, 628.3 ms before and 47.6 ms after; Back to the tea list, 463.9 ms before and 30.9 ms after; Back to home, 44.3 ms before and 26.7 ms after; Forward to the tea list, 476.9 ms before and 27.1 ms after; Forward to Mint tea, 42.4 ms before and 28.2 ms after.Before: 500 ms after the clickAfter the project: 500 ms after the clickThe tea list, still on screen half a second after the clickThe Mint tea page, with its photo, half a second after the clickStill the tea listThe Mint tea pageFrom the press to the largest content on screen, in msHome to the tea list637.0238.6The tea list to Mint tea628.347.6Back to the tea list463.930.9Back to home44.326.7Forward to the tea list476.927.1Forward to Mint tea42.428.2beforeafter the project
The top frames are what Chrome drew, 500 ms after the click. Under them, each pair of bars is one navigation: before the project (shaded) and after it. The bars count from the press to the page's largest content on screen.

Each step of the project does one job. A good library helper does all of them:

Real-life analogyA library helper who thinks ahead

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

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.

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:

Why wasn't this page restored?JavaScript
// 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 null on 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.

Real-life analogyFallen trees on a forest road

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

analytics.js, fixedJavaScript
// analytics.js: counts each page view, and how long the visitor stayed.let started = performance.now();const send = (data) => navigator.sendBeacon("/visit", JSON.stringify({ page: location.pathname, ...data }));send({});addEventListener("pagehide", () => send({ stayed: Math.round(performance.now() - started) }));addEventListener("pageshow", (event) => {  if (!event.persisted) return;  started = performance.now();  send({ restored: true });});
  • Line 4 counts the page view.
  • Line 5 sends the time on the page from pagehide. It used to say unload. pagehide fires 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:

serve.mjs, lines 8 to 10, after step 1JavaScript
const PAGE = { "cache-control": "no-cache", "permissions-policy": "unload=()" };const HEADERS = {  "/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:

Playground: read notRestoredReasons, fix by fix
Each trip back or forwardBefore
  1. 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
  2. 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
  3. 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
  4. 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
Try it yourself
Before: 0 of 4 trips restored

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.

Recorded in all five trips at each version, with the same reasons each time.

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:

serve.mjs, lines 8 to 12, beforeJavaScript
const PAGE = { "cache-control": "no-cache" };const HEADERS = {  // The tea list shows what's in stock, so it must never be stale.  "/teas.html": { "cache-control": "no-store" },  "/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.

app.js, before: the channelJavaScript
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.

app.js, fixed: close it, and open it againJavaScript
let channel;const listen = () => {  channel = new BroadcastChannel("cart");  channel.onmessage = show;};listen();show();addEventListener("pagehide", () => channel.close());addEventListener("pageshow", (event) => {  if (!event.persisted) return;  listen();  show();});
  • 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".

app.js, fixed: the guide opens on its ownJavaScript
document.querySelector("#guide")?.addEventListener("click", () => {  window.open("brewing.html", "guide", "popup,width=420,height=560,noopener");});

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:

Four things kept the store's pages out of the back/forward cache. an unload listener: Chrome said masked (DevTools: an unload handler); the fix: pagehide. no-store on the list: Chrome said response-cache-control-no-store (a cookie changed while it waited); the fix: no-cache. a BroadcastChannel: Chrome said broadcastchannel-message (a message came while it waited); the fix: close(). window.open(): Chrome said non-trivial-browsing-context-group (it had opened a window); the fix: noopener.What the store didWhat Chrome saidThe fixan unload listenermaskedDevTools: an unload handlerpagehideno-store on the listresponse-cache-control-no-storea cookie changed while it waitedno-cachea BroadcastChannelbroadcastchannel-messagea message came while it waitedclose()window.open()non-trivial-browsing-context-groupit had opened a windownoopener
Each row is one blocker. The middle is the reason 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:

The rules in the tea list's headHTML
<script type="speculationrules">{  "prefetch": [{ "where": { "href_matches": "/*" }, "eagerness": "moderate" }],  "prerender": [{ "urls": ["/mint-tea.html"] }]}</script>
  • Lines 1 and 6 hold a speculationrules script. The browser reads JSON there, not JavaScript.
  • Line 3 is a prefetch rule. where picks every link whose address matches /*: any page of the store. moderate says 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.
Real-life analogyA café cook who watches the room

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:

A timeline in ms from Asha's click on Teas, drawn to scale. The tea list was on screen at 239.2 ms. Chrome asked for the Mint tea page at 242.8 ms and had it built, hidden, by 674.4 ms. Asha clicked Mint tea at 3,725 ms, and its largest content was on screen 38.1 ms later.Tea liston screen at 239.2 msMint tea, hiddenbuilt from 242.8 to 674.4 msMint tea, shownclick at 3,725 ms, on screen 38.1 ms later0 ms1,000 ms2,000 ms3,000 msactivationStart: 3,451.4
The Mint tea page was ready about three seconds before Asha wanted it. Her click only had to show it. Its 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:

How the Mint tea page arrivedPop out in the code editor (opens in a new tab)JavaScript
// The Mint tea page Asha saw: its navigation entry, and what web-vitals reported.const entry = { deliveryType: "navigational-prefetch", activationStart: 3451.4 };const webVitals = { navigationType: "prerender", lcp: 33 }; console.log(`Delivered by ${entry.deliveryType}, built ${entry.activationStart} ms before it was shown.`);console.log(`web-vitals: ${webVitals.navigationType}, LCP ${webVitals.lcp} ms.`);
  • Line 2 holds two fields of the navigation entry. deliveryType is "navigational-prefetch": the HTML came from a fetch made ahead of time. activationStart is 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. and web-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:

analytics.js: count a prerendered page when it's shownJavaScript
const shown = () => {  started = performance.now();  send({});  addEventListener("pagehide", () => send({ stayed: Math.round(performance.now() - started) }));};// A prerendered page starts counting when the visitor sees it, not while Chrome builds it.if (document.prerendering) document.addEventListener("prerenderingchange", shown, { once: true });else shown();
  • Lines 1 to 5 make a shown() function. It starts the clock, counts the view, and listens for pagehide.
  • Line 7 waits while the page is prerendering. prerenderingchange fires 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:

styles.css, the first tryCSS
@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: auto asks 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:

The tea list's console, after the clickText
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:

The opt-in, in each page's headHTML
<style>  @media (prefers-reduced-motion: no-preference) {    @view-transition { navigation: auto; }  }</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.

Four real frames after Asha clicked Mint tea, with the view transition. At 53.1 ms: the tea list. At 119.8 ms: both, fading. At 169.7 ms: mostly Mint tea. At 336.4 ms: Mint tea.53.1 msThe screen 53.1 ms after the click: the tea listthe tea list119.8 msThe screen 119.8 ms after the click: both, fadingboth, fading169.7 msThe screen 169.7 ms after the click: mostly Mint teamostly Mint tea336.4 msThe screen 336.4 ms after the click: Mint teaMint tea
The old page fades out while the new one fades in. Chrome reported Mint tea's largest content at the start of the fade, not at its end.

What the fade costs

Real-life analogyLift doors

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:

The click on Mint tea, with and without the fadePop out in the code editor (opens in a new tab)JavaScript
// The middle of five trips, in ms from the click on Mint tea.const without = { lcp: 38.1 };const withFade = { lcp: 47.6, fadeEnded: 304 }; console.log(`LCP: ${without.lcp} ms, then ${withFade.lcp} ms with the fade`);console.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 fade and The 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:

Playground: Asha's trip at every checkpoint
From the press to the pageBefore
  1. Home to the tea list637.0 msLoaded from the network.
  2. The tea list to Mint tea628.3 msLoaded from the network.
  3. Back to the tea list463.9 msLoaded from the network.
  4. Back to home44.3 msLoaded again, from the HTTP cache.
  5. Forward to the tea list476.9 msLoaded from the network.
  6. Forward to Mint tea42.4 msLoaded again, from the HTTP cache.
Try it yourself
Before: 2 of 6 navigations under 100 ms

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.

The middle of five trips in the lab: Chrome 157.0.8103.52, the CPU 4× slower, Fast 4G.

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:

rum.js: the navigation typeJavaScript
onLCP(({ value, navigationType, attribution: a }) => {  beacon.nav = navigationType;  beacon.lcp = { value, element: a.target ?? null, parts: [a.timeToFirstByte, a.resourceLoadDelay, a.resourceLoadDuration, a.elementRenderDelay] };});
  • Line 1 takes navigationType from web-vitals' report, along with the LCP.
  • Line 2 keeps it in the beacon. web-vitals says navigate, back-forward when Back loaded the page again, back-forward-cache after a restore, and prerender.

Second, a restored page is a new page view, so it gets a new beacon:

rum.js: a new beacon after a restoreJavaScript
let sent = false;// A page restored from the back/forward cache is a new page view: start a new beacon.addEventListener("pageshow", (event) => {  if (!event.persisted) return;  beacon = start();  sent = false;});
  • 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:

collector.mjs: the navigation typesJavaScript
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:

by-navigation.mjsJavaScript
// by-navigation.mjs: page views and LCP p75 for each way a page arrived. Run it with: node by-navigation.mjsimport { readFileSync } from "node:fs"; const FILE = process.argv[2] ?? "beacons.jsonl";const beacons = readFileSync(FILE, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line));const p75 = (values) => values.toSorted((a, b) => a - b)[Math.ceil(values.length * 0.75) - 1]; const withLcp = beacons.filter((beacon) => beacon.lcp);const groups = Object.groupBy(withLcp, (beacon) => beacon.nav);for (const [nav, views] of Object.entries(groups).sort((a, b) => b[1].length - a[1].length)) {  const share = Math.round((views.length / withLcp.length) * 100);  console.log(`${nav}: ${views.length} page views (${share}%), LCP p75 ${Math.round(p75(views.map((view) => view.lcp.value)))} ms`);}
  • 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:

The field, before the projectText
navigate: 140 page views (61%), LCP p75 412 ms
back-forward: 90 page views (39%), LCP p75 328 ms
The field, after the projectText
navigate: 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 ms
Real-life analogyTiming parcels by service

A 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:

Which step makes this trip instant?
  • 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
Try it yourself
0 of 6 correct

Sort each navigation by what made it fast on the finished store.

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

Read the table across: each row is one way a page arrives, and how to tell.

How a page arrived, and how to tell
How the page arrivedWhat the page can readWhat 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 masked for 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.css arrived 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.

Exercise 1 · Warm-upHalfway through step 1

After fix 2, the course counted the trips back and forward in five trips. What does it print?

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

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

    Exercise 2 · Warm-upName the page view

    This is how web-vitals names a page view, shortened. What does the last line print?

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

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

      Exercise 3 · PracticeThe fade on Back

      At Step 3, when did the fade end on Back to home, in ms?

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

        Exercise 4 · PracticeDevTools' name for no-store

        After fix 1, which reason did DevTools' protocol give, under Actionable, on Back to the tea list?

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

          Exercise 5 · ChallengeThe prefetch in DevTools

          Open the store after step 2 in Chrome. What does the tea list request's Sec-Purpose header say?

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

            Exercise 6 · ChallengeOnly on a press

            Read Prerender pages in Chrome. Which eagerness waits until the visitor presses the link?

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

              Check your understanding

              For each question, ask which kind of navigation it is about, and how that page arrived.

              The instant navigations quiz · 7 questionsScore: first tries count
              1. Question 1 of 7Before the first fix, Back to the tea list gave only masked in notRestoredReasons. What does that mean?

                Choose an answer to see the explanation.

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

              3. Question 3 of 7Why does app.js close its BroadcastChannel on pagehide?

                Choose an answer to see the explanation.

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

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

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

              7. Question 7 of 7What does this print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const 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:

              The reader's field files are published too:

              Coming next: Project: an image pipeline. You'll build a pipeline that turns the store's photos into the right sizes and formats.

              CompleteFrontend Clear concepts. Working examples.