Debugging Web Performance / Module 04

Module 4: The Second Visit and the Next Click

Find what keeps a page out of the back/forward cache, set cache headers for the second visit, and prerender the next page, measured in Chrome.

On the Monday after the stadium sale, Leo forwarded a message from a buyer. She had picked two seats, opened checkout to see the total, and pressed Back to change one. The seat map loaded again from the start, and her two seats were no longer picked.

“Did we lose her seats?” Leo wrote.

“No, the server still holds them,” Maya wrote back. “The page forgot them. Her phone built it again from nothing.”

Maya, Leo and TinyTickets are invented, and so are the numbers in their story.

Modules 1 to 3 measured first visits with the cache turned off. But this module is about every view after the first: pressing Back, coming back later, and clicking the next link. You’ll find out what the browser keeps between views, why it threw the seat map away, and how to start the next page before the buyer clicks.

After this module, you can:

  • predict from a response’s headers whether the browser reuses it, asks the server first or downloads it again, and check it in the Network panel
  • find what keeps a page out of the back/forward cache with the DevTools tester and notRestoredReasons, and fix it without showing old data
  • choose cache headers for HTML, for files whose name changes with their content, and for files whose name doesn’t, and say what each choice costs
  • start the likely next page before the click with the Speculation Rules API, and name what prefetch and prerender cost
  • split field data by navigation type, so a restore or a prerender isn’t counted as a first load

What buyers saw when they pressed Back

Buyers move between three pages: the show page, the seat map and checkout. Checkout shows the seats and the total, and opening it holds the seats for that buyer for a few minutes. Many buyers check the total and go back to change a seat.

Maya’s endpoint from Module 1 could not tell a Back from a first load. So she added one field to vitals.js. web-vitals gives every metric a navigationType, and the queue now keeps it:

  queue.set(metric.id, {
    page: location.pathname,
    device,
    name: metric.name,
    value: metric.value,
    rating: metric.rating,
    navigationType: metric.navigationType,
    id: metric.id,
    ...attribution,
    script: script && `${script.invoker} in ${script.sourceURL}`,
  });

That’s an excerpt of public/vitals.js; the new line is navigationType. The values include navigate for a normal load, reload, back-forward for a Back or Forward that loads the page again, back-forward-cache for a page restored from memory, and prerender (web-vitals). p75.js now groups by it too:

// navigationType tells a first load from a Back restore or a prerender. Older lines lack it.
const groups = Map.groupBy(latest.values(), (r) => `${r.page} ${r.device} ${r.navigationType ?? 'unknown'} ${r.name}`);

Three days later, the seat map on phones had 2,310 LCP lines with back-forward, and their 75th percentile was 3.9 s. There was no line with back-forward-cache. CrUX told the same story: on phones, 12% of the seat map’s page loads in the last 28 days were Back or Forward, and 0% came from the back/forward cache.

Pause and predict. A buyer presses Back from checkout. Which of the seat map’s files does the browser request from the server again: all of them, the HTML only, or none?

Build checkout and reproduce the reload

Checkout is a new page in the lab app from Module 3. It needs four small changes.

public/checkout.html lists the seats and loads the payment provider’s widget from the second origin. It’s a fake; Module 7 measures what a real widget costs.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Checkout - TinyTickets</title>
  <link rel="stylesheet" href="/styles.css">
  <script src="http://127.0.0.1:8081/analytics.js"></script>
  <script type="module" src="/vitals.js"></script>
</head>
<body>
  <header>TinyTickets</header>
  <main>
    <h1>Checkout</h1>
    <p id="summary">Midsummer Lights, June 20</p>
    <div id="payment"></div>
  </main>
  <script src="/checkout.js"></script>
  <script src="http://127.0.0.1:8081/payment.js" async></script>
</body>
</html>

public/checkout.js reads the seats from the address and writes the total:

// Lists the seats from the address, such as /checkout.html?seats=12,13, and the total.
const ids = new URLSearchParams(location.search).get('seats')?.split(',').map(Number) ?? [];
const total = ids.reduce((sum, id) => sum + (id < 20000 ? 95 : 60), 0);
document.getElementById('summary').textContent =
  `Midsummer Lights, June 20. ${ids.length} seats, $${total}.`;
document.getElementById('payment').dataset.total = total;

third-party/payment.js draws a Pay button:

// A fake payment widget, served from a second origin like a real one. Module 7 weighs it.
const box = document.getElementById('payment');
box.innerHTML = `<button type="button">Pay $${box.dataset.total}</button>`;

On the seat map, add a link under the map in public/seats.html:

    <p><a id="checkout" href="/checkout.html">Continue to checkout</a></p>

In public/seats.js, find the link after status, and point it at the picked seats at the end of render():

const checkout = document.getElementById('checkout');
  status.textContent = `${free} seats free, ${picked.size} picked`;
  checkout.href = `/checkout.html?seats=${[...picked].join(',')}`;

The last change copies two headers that TinyTickets’ production server sent on sale day. In serveFile in server.js, collect the headers in an object and add two lines:

    const headers = {
      'Content-Type': TYPES[extname(path)] ?? 'application/octet-stream',
      // Tells the browser where the server spent its time on this response.
      'Server-Timing': `delay;dur=${delay}, read;dur=${read};desc="read file"`,
    };
    // Sale day: no buyer may see an old seat map.
    if (url.pathname === '/seats.html') headers['Cache-Control'] = 'no-store';
    // Opening checkout holds the seats for this buyer.
    if (url.pathname === '/checkout.html') headers['Set-Cookie'] = `hold=${Date.now()}; Path=/; SameSite=Lax`;
    res.writeHead(200, headers);

Maya added no-store before the sale so that no buyer would see seats that were already sold. The cookie stands in for the hold; the real one names a hold on the server.

Now set the phone profile from Module 1: 412 × 823 with touch, device pixel ratio 1, Slow 4G and 6x CPU. But leave one thing different from Modules 1 to 3: uncheck Disable cache. Every earlier run measured a first visit, and a Back isn’t one.

Open http://localhost:8080/seats.html, pick two seats, click Continue to checkout, then press Back. After Back, paste this into the Console:

const nav = performance.getEntriesByType('navigation')[0];
console.log(`type: ${nav.type}, notRestoredReasons: ${JSON.stringify(nav.notRestoredReasons?.reasons ?? null)}`);
console.log(`seats picked: ${document.querySelectorAll('.seat.picked').length}`);

Here’s the output of one run. Your numbers in this module will differ, but the order of events shouldn’t.

type: back_forward, notRestoredReasons: [{"reason":"response-cache-control-no-store"}]
seats picked: 0

This module’s runs use headed Chrome 157 (a normal window) on the 2019 laptop from Modules 1 to 3, driven through the DevTools Protocol. Modules 1 to 3 used headless Chrome. Prerendering, at the end of this module, didn’t run in headless Chrome, so this module uses one browser setup for every step.

In four runs, the seat map’s first visit had an LCP of 4,752 to 4,892 ms. After Back, it loaded again, with an LCP of 3,444 to 3,480 ms. The two picked seats were gone each time.

Figure 1 is the page-load timeline of that Back, from one run. It adds no new kind of row; what’s new is that most files have no bar.

time (s)     0         1         2         3         4
             |         |         |         |         |
seats.html   ======                              from the network (no-store)
styles.css         |                             from the cache, no request
analytics.js       |                             from the cache, no request
vitals.js          |                             from the cache, no request
seats.js           |                             from the cache, no request
stadium-400        |                             from the cache, no request
main thread        [= JS =][=== rendering ====]
                   ^ TTFB 0.56 s
                 LCP 3.44 s (stadium-400.avif) ^

Figure 1: on Back, only the HTML went to the network, and the main thread still built 60,000 seats again.

The answer to the prediction is the HTML only. The LCP parts of that run were TTFB 564 ms, load delay 35 ms, load duration 0 ms and render delay 2,845 ms. The network cost one round trip, and the main thread cost the rest: seats.js built and rendered the map, then the browser laid out and painted it (Module 2).

The lab’s 3.4 s is close to the field’s 3.9 s, because the page’s own work dominates both.

Where a second view comes from

A view after the first can reuse work from three places. Figure 2 compares them; the rest of this module uses them in this order.

HTTP cache Back/forward cache Speculation rules
What it keeps responses: headers and bytes the whole page, with its JavaScript heap a page fetched or rendered before the click
When it is used any load that requests the same URL Back and Forward only the next click on a matching link
What still runs parsing, all JavaScript, style, layout, paint almost nothing: the page resumes after a prerender, the work left at activation
Who decides the response’s headers the browser, page by page the page, with rules

Figure 2: the HTTP cache saves the network; the other two also save the main thread.

The HTTP cache decides with freshness and validators

You know Cache-Control. This part is about the rules the browser applies to it, because they explain what happened to the six files in Figure 1.

A response’s freshness lifetime is how long a cache may reuse it without asking the server. max-age sets it, or Expires when there’s no max-age (RFC 9111, section 4.2.1). While the response is fresh, the browser doesn’t send a request at all.

When a stored response is stale, the browser can ask the server whether it changed. Revalidation is that question: a conditional request with If-None-Match (the stored ETag) or If-Modified-Since, answered by 304 Not Modified with no body when nothing changed (RFC 9111, section 4.3). A 304 still costs a round trip, but not the bytes.

no-cache means “store it, but revalidate before every use”. no-store means “do not store it at all” (RFC 9111, section 5.2.2). MDN puts the common mistake in one line: no-cache doesn’t mean “don’t cache” (MDN). Figure 3 shows the path one request takes.

request for a URL
  |
  +-- no stored response, or it was no-store  -> full request, 200
  |
  +-- stored and fresh (inside max-age)       -> no request at all
  |
  +-- stored and stale (or no-cache)
        +-- has ETag or Last-Modified          -> conditional request
        |                                         304: reuse the bytes
        |                                         200: replace them
        +-- has neither                        -> full request, 200

Figure 3: a request reaches the server only when the stored copy is missing or stale.

The lab server sends no Cache-Control, no ETag and no Last-Modified for any file except the seat map. That’s not “no caching”. When a response has no explicit lifetime, a cache may compute one, which is heuristic freshness. The RFC suggests 10% of the time since Last-Modified (RFC 9111, section 4.2.2), and Chrome uses exactly that (Chromium source, GetFreshnessLifetimes()). Suppose a file was last changed 30 days before the download. Then it’s fresh for 3 days.

So a static file served with Last-Modified and nothing else is reused for days, and nobody chose that. That’s why a deploy that changes it can look broken for some buyers until their copy turns stale. Chrome treats a 301 without Cache-Control as fresh forever, by the same function. But the lab’s files have no Last-Modified, so their heuristic lifetime is 0: stored, and stale at once.

That explains why the five files in Figure 1 came from the cache with no request. RFC 9111 allows a history mechanism such as Back to show a stored response “even if it has expired” (section 6). Chrome loads a Back or Forward with the cache mode kForceCache, which uses any stored response, fresh or stale (Chromium source, frame_fetch_context.cc). Only seats.html went to the network, because no-store left nothing to reuse.

Two more details matter when you read the Network panel:

  • Memory cache and disk cache. A renderer keeps recent responses in memory for the pages it shows. A new tab or a new process falls back to the disk cache. The research runs saw both, through the protocol’s fromDiskCache field.
  • Disable cache is more than an empty cache. With it checked, Chrome sends Cache-Control: no-cache on each request and drops the validators. So the server never gets a chance to answer 304.

A normal reload is a third case. Since early 2017, Chrome revalidates only the page’s HTML on reload and reuses fresh subresources, which cut validation requests by 60% in Facebook’s data (Chromium blog).

Each site gets its own cache

Cache partitioning means the browser keys each stored response by the site that requested it as well as by its URL. Since Chrome 86 (2020), the key is the URL plus the top-level site and the frame’s site (Chrome for Developers). Firefox has partitioned by top-level site since version 85 (2021), and Safari partitions third-party content per website (Mozilla, WebKit).

So a library on a shared public CDN isn’t “already cached” from another site, in any of the three engines. Chrome measured the cost when it shipped: a 3.6% higher cache miss rate and about 0.3% slower FCP. CDNs and edge caching, the server side of caching, are System Design Module 4.

Chromium’s code today also keeps a separate entry for a top-level page reached from another site, such as a link in an email (Intent to Ship, 2025). So a buyer who opens the seat map from an email doesn’t reuse the HTML stored by a click inside TinyTickets.

The back/forward cache keeps the whole page

The HTTP cache saved Figure 1 its downloads, but the main thread still spent 2.8 s. Only a cache that keeps the built page can save that.

The back/forward cache (bfcache) keeps a page in memory when the buyer leaves it, with its DOM and JavaScript heap, and shows it again on Back or Forward (web.dev). Timers and pending promises pause when the page is stored and continue on restore. No script runs again, so the load event doesn’t fire again either.

It matters because Back is common. web.dev reports that 1 in 10 navigations on desktop and 1 in 5 on mobile are Back or Forward, from Chrome usage data. Figure 4 shows a page’s path through the cache, with the course’s symbols.

(Buyer) --> [Seat map] --leave--> pagehide, persisted: true
                                  |
                                  v
                          [[bfcache: the frozen page]]   up to 10 minutes
                                  |
(Buyer) --Back--------------------+--> pageshow, persisted: true
                                       the page continues where it stopped

Figure 4: a page that’s stored isn’t loaded again; it continues.

The pageshow event fires after the first load, and again on every restore. Its persisted property is true when the page came from the back/forward cache, and false on a normal load (MDN). On pagehide, persisted: true means the browser intends to store the page, not that it will.

A restored page keeps the navigation entry it had at its first load. That’s why the Console snippet prints type: navigate after a restore, and why field code must listen to pageshow. In Chrome, a stored page is dropped after 10 minutes, or after 3 minutes if it was sent with no-store (Chrome for Developers).

What keeps a page out

Not every page can be stored. The HTML Standard lists the reasons a browser may give, from unload-listener to response-cache-control-no-store (HTML Standard). But each browser decides which ones block. Figure 5 compares the ones a ticket site is likely to hit.

The page has Chrome 157 Firefox Safari
An unload listener not a blocker for users since Chrome 155; blocks if the site opts back in blocks stores the page, does not run the handler
Cache-Control: no-store stored since 2025, with conditions may block may block
no-store, and a cookie changes while it is stored dropped as above as above
no-store, and a fetch() response with no-store dropped as above as above
An open WebSocket stored since Chrome 149; the socket is closed blocks stored

Figure 5: Chrome now stores no-store pages, but drops them when a cookie changes. Sources: web.dev, Chrome on no-store, Chrome on unload, Chrome 149.

The second and third rows are the seat map. Chrome stores a no-store page, but “will evict a page from the bfcache on changes to cookies, or other authorization methods” (Chrome for Developers). Opening checkout sets the hold cookie, so the stored seat map is dropped while the buyer is on checkout.

notRestoredReasons is a property of the navigation timing entry that lists why the last Back or Forward didn’t restore the page (Chrome for Developers). It names the page’s own reasons, and a cross-origin frame’s reasons only as masked. It’s null when the load wasn’t a Back or Forward, and also when nothing blocked, so check persisted to know which. It shipped in Chrome 123 (2024) and was fully available from 125; Firefox and Safari don’t have it.

Find the cause on Back

The steps below follow one Back from checkout with the files above.

  1. Watch the Network panel during Back. Keep Disable cache unchecked and turn on Preserve log. Press Back. Only seats.html comes from the network; the other files are served from the cache, as in Figure 1.

  2. Read the reason in the Console. The snippet printed response-cache-control-no-store and 0 picked seats. The same reason, sent from the field, is how Maya would see this on real phones.

  3. Run the DevTools tester. Open Application > Background services > Back/forward cache and click Test back/forward cache. It leaves the page for chrome://terms/ and comes back, then lists blockers under Actionable, Pending Support and Not Actionable (Chrome for Developers).

Pause and predict. The tester goes to chrome://terms/, not to checkout. Will it find a blocker on the seat map?

Answer

Probably not, and that’s the trap. The seat map is dropped only when a cookie changes while it is stored, and chrome://terms/ sets no cookie. In a run without the cookie, the same no-store seat map was restored in 37 ms. So test the real path: go to checkout and press Back.

  1. Ask the protocol for Chrome’s own reason. DevTools gets its blocker list from the protocol event Page.backForwardCacheNotUsed. For the real Back from checkout, it named one reason:
PageSupportNeeded:CacheControlNoStoreCookieModified

That’s more precise than the page’s response-cache-control-no-store. The tester shows these reasons with their own descriptions.

  1. Change one thing at a time. Two variants of the server, one run each, answered the question in step 3. Without the cookie and with no-store, the page was restored, with LCP 37 ms. Without no-store and with the cookie, it was restored too, with LCP 35 ms. So the cause is the pair, and either change alone fixes Chrome.

  2. Check the test browser itself. In one more variant, analytics.js added an unload listener and the seat map had no no-store. In this fresh test profile, Back didn’t restore the page. The protocol named UnloadHandlerExistsInMainFrame, and notRestoredReasons said only masked.

Step 6 disagrees with Chrome’s documentation for users, which says the unload deprecation reached 100% in Chrome 155. But the rollout reaches users through Chrome’s own servers, and a fresh test profile didn’t have it. So a browser in a test or CI setup can disagree with what your users get.

Rule: Test Back on the real path, from the real next page, and read the reason in the field as well as in DevTools.

The fixes, one change at a time

Each fix below changes one thing. Every number comes from the phone profile in headed Chrome 157, and each step was measured three times unless a line says otherwise.

Fix 1: let the seat map into the back/forward cache

no-store was there to keep seat availability current. But a stored page can do that itself: when it’s restored, ask the server what changed. In server.js, delete the no-store line, and add a small endpoint before serveFile is called:

createServer((req, res) => {
  if (req.method === 'POST' && req.url === '/vitals') return saveVitals(req, res);
  // A fake: the seats other buyers took in the last minutes. The lab always says 3, 4 and 11.
  if (req.url === '/api/sold') {
    return res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }).end('[3, 4, 11]');
  }
  return serveFile(req, res, app);
}).listen(8080);

At the end of public/seats.js, refresh the seats on a restore:

// A page restored from the back/forward cache still shows the seats as they were. Ask again.
addEventListener('pageshow', async (event) => {
  if (!event.persisted) return;
  const sold = await (await fetch('/api/sold')).json();
  for (const id of sold) {
    seats[id].sold = true;
    picked.delete(id);
  }
  render();
});

The endpoint keeps no-store. That’s safe now, because the page itself is no longer no-store, and Chrome drops only no-store pages for a no-store fetch.

Back from checkout was restored in every run. LCP, as web-vitals measures a restore, was 28 to 35 ms, from pageshow to the next frame. The two picked seats were still there. The Console snippet printed:

type: navigate, notRestoredReasons: null
seats picked: 2

Figure 6 is the same Back after the fix, on a finer time scale.

time (s)     0         0.2       0.4       0.6       0.8       1.0
             |         |         |         |         |         |
seats.html   | restored from memory, no request                  NEW
/api/sold    =============================                       NEW
main thread                               [==== render ====]     NEW
              ^ LCP 0.03 s: the map as the buyer left it, 2 seats picked

Figure 6: the map is back at once; the sold seats arrive half a second later.

The refresh took one request of about 0.57 s, then render() ran for 354 to 368 ms. The status line changed from “23998 seats free” to “23995 seats free, 2 picked”, because seats 3, 4 and 11 were sold.

The costs:

  • The buyer sees old data for a moment. For about half a second, sold seats look free. So a tap on one in that time must fail on the server, as it already must for any race between two buyers.
  • render() blocks the main thread for 0.36 s on the phone profile. A tap in that time waits. Module 5 makes render() cheaper.
  • Memory. The stored page keeps its 60,000 elements in memory for up to 10 minutes. The browser drops it under memory pressure, which phones reach sooner.
  • Every restore path needs the same care. Anything that can change while the page is stored needs a pageshow check: availability, the cart, the sign-in state.

The alternatives, and when the choice flips:

  • Keep no-store and stop changing cookies while the page is stored. Chrome would then restore it. But Firefox and Safari may still refuse a no-store page, and the hold would need a place other than a cookie.
  • Save the picked seats in sessionStorage and read them on every load. The seats survive a reload, but the 2.8 s rebuild stays. It’s still useful for the buyers who don’t get a restore.
  • Make the map cheaper to build, which Modules 5 and 6 do. That helps every load, and a restore is still faster.

Fix 2: cache headers for the second visit

Suppose a buyer comes back tomorrow. They don’t press Back. They open the seat map again, and that’s a new navigation, where kForceCache doesn’t apply. The lab measured it as seat map, then show page, then the seat map again by a new navigation.

Before this fix, the second visit downloaded all seven files again in full: 36,274 bytes, with status 200 each. Its LCP was 4,148 to 4,688 ms. A trace of the seat map failed the Use efficient cache lifetimes insight, which listed six files with a lifetime of 0 s, about 35 KB in all.

The insight ignores a file whose lifetime gives it a cache hit probability above 92.5%. It estimates that probability from old Chrome data about the age of reused files (DevTools source). It also counts any no-cache or no-store as an intentional choice, and doesn’t list it.

The rule for this lab: a picture never changes under the same name, because a new picture gets a new file name. Every other file can change under its name, so it’s checked with its ETag on each use. First, in server.js, import a hash function at the top:

import { createHash } from 'node:crypto';

Then add the rule above serveFile:

// Pictures never change under the same name. Every other file is checked with its ETag on each use.
function cacheControl(path) {
  return ['.jpg', '.avif'].includes(extname(path)) ? 'max-age=31536000, immutable' : 'no-cache';
}

In serveFile, add an ETag from the file’s content, and answer 304 when the browser already has it:

    const etag = `"${createHash('sha256').update(body).digest('base64url').slice(0, 16)}"`;
    const headers = {
      'Content-Type': TYPES[extname(path)] ?? 'application/octet-stream',
      // Tells the browser where the server spent its time on this response.
      'Server-Timing': `delay;dur=${delay}, read;dur=${read};desc="read file"`,
      'Cache-Control': cacheControl(path),
      ETag: etag,
    };
    // Opening checkout holds the seats for this buyer.
    if (url.pathname === '/checkout.html') headers['Set-Cookie'] = `hold=${Date.now()}; Path=/; SameSite=Lax`;
    if (req.headers['if-none-match'] === etag) return res.writeHead(304, headers).end();
    res.writeHead(200, headers);

The Set-Cookie line moves above the 304 check, so a revalidated checkout still holds the seats. The third-party server uses the same function, so analytics.js gets no-cache too.

After the change, the second visit sent six conditional requests and got six 304 responses, 1,601 bytes in all. The picture came from the cache with no request. FCP stayed at 1,224 to 1,232 ms, and LCP fell to 1,224 to 1,232 ms. The trace passed the cache insight.

Why did LCP fall by 3 s when the network only saved 35 KB? The picture was already in the cache, so it was ready for the first frame, at 1.22 s. But before the fix, it arrived 0.77 s after its request, and by then seats.js was building the map, so the paint waited for the main thread. The map itself still took the same main-thread time; LCP measures the picture.

Versioned URLs, and a result to predict

The 304s still cost a round trip each. If you want to remove them, the URL must change whenever the content changes. A versioned URL is a file name or query that includes a version or a hash of the content, such as seats.3f9a1c.js, so a changed file is a new URL. Then every file except the HTML can have max-age=31536000, immutable: the old URL never changes, and the HTML points to the new one (web.dev).

The lab has no build step to rename files; Module 7 adds a bundler that does it. So to measure the effect without one, a variant of the server gave every file except the HTML the year-long lifetime.

Pause and predict. With that variant, the second visit sends one request (the HTML, 304) instead of six. Will its FCP be earlier or later than 1.22 s?

Answer

Later. FCP and LCP were both 3,420 ms in two runs; a third run did not record them. Every file came from the cache at once, so the parser ran seats.js before the browser painted anything, and the first frame waited for the 60,000 seats.

But with 304s, the parser waited about 0.56 s for seats.js, and the browser painted the header and the picture in that wait.

Figure 7 puts the three versions side by side.

Second visit Requests Bytes over the network FCP LCP
No cache headers (after Fix 1) 7, all 200 36,274 1,220–1,232 ms 4,148–4,688 ms
Fix 2: pictures immutable, the rest no-cache + ETag 6, all 304 1,601 1,224–1,232 ms 1,224–1,232 ms
Variant: every file but the HTML immutable 1 (304) 263 3,420 ms 3,420 ms

Figure 7: the fewest requests gave the latest first paint, because the main thread, not the network, decides this page.

The lab keeps Fix 2. The variant’s result belongs to seats.js, which runs one long task before the first frame; Modules 5 and 6 break it up. But on a page without such a task, versioned URLs with a year-long lifetime are the common choice.

The costs of Fix 2:

  • A round trip per file on every new visit, 0.56 s on Slow 4G, although the requests run in parallel.
  • A wrong immutable can’t be taken back. A buyer keeps a year-long file for a year. So use it only for URLs that change when the content changes.
  • immutable does nothing in Chrome. Chrome doesn’t support it; Firefox does since 49 and Safari since 11. But Chrome rarely needs it, because its reload revalidates only the HTML.
  • ETags must match across servers. Some servers build the ETag from something that differs per machine, such as a file’s inode. Then a revalidation that reaches another server returns 200. A hash of the content, as here, is the same everywhere.

The alternatives:

  • stale-while-revalidate lets the browser use a stale copy for a window while it revalidates in the background: max-age=60, stale-while-revalidate=3600. It works in Chrome 75, Firefox 68 and Safari 14 (web.dev). It fits a file where a minute-old copy is acceptable. But never use it for seat availability.
  • A service worker can decide per request in code, and it sees requests before Cache-Control applies. But it’s a whole new part of the app, and this course doesn’t cover it.

Fix 3: start the seat map before the click

Two pages are now fast on the second view. But the first visit to the seat map isn’t: a buyer who taps Buy tickets on the show page still waits for the whole map. The lab measured that click with Fix 2 in place. The picture painted at 1,240 to 1,256 ms after the click, and the first frame with the map came at 4,239 to 4,316 ms.

The show page knows where most buyers go next. The Speculation Rules API is a JSON block in a <script type="speculationrules"> element, or in a Speculation-Rules header, that tells the browser which pages to load before the click (MDN). It offers two actions:

  • Prefetch downloads the next page’s HTML only, and keeps it in memory for the next navigation. Chrome keeps it for 5 minutes.
  • Prerender loads the whole page in an invisible tab: it fetches the subresources, renders the page and runs its JavaScript. A click then shows that page without loading it again.

Speculation rules prefetch is part of the HTML Standard (section 7.6); prerender is still a WICG draft (Prerendering Revamped). Prefetch saves the HTML’s round trip and nothing on the main thread. But the seat map’s wait is mostly the main thread, so prerender is the action that fits. A rule also has an eagerness: how early the browser acts on it (Chrome for Developers).

Eagerness Desktop Mobile Prerenders kept at once
immediate as soon as the rule is seen same 10
eager 10 ms of hover 50 ms after the link enters the viewport 2 (oldest dropped first)
moderate 200 ms of hover 500 ms after scrolling stops, by viewport heuristics 2
conservative pointer or touch down same 2

Figure 8: the less eager the rule, the fewer pages are loaded for nothing. Source: Chrome for Developers, updated 2026-11-13.

A rule with a list of URLs defaults to immediate. But a rule with a where condition defaults to conservative. Add one rule to the <head> of public/show.html:

  <script type="speculationrules">
    { "prerender": [{ "where": { "href_matches": "/seats.html" }, "eagerness": "moderate" }] }
  </script>

The rule prerenders the seat map when a link to it gets 200 ms of hover on desktop, or by Chrome’s viewport rules on a phone. Figure 9 shows what the server saw in one run, with the course’s symbols.

(Buyer) --hovers Buy tickets--> [Chrome]
[Chrome] --> [TinyTickets web app]   GET /seats.html
                                     Sec-Purpose: prefetch;prerender   NEW
[Chrome] --> [TinyTickets web app]   GET /styles.css, /seats.js, ...
                                     Sec-Purpose: prefetch;prerender   NEW
(Buyer) --clicks------------------> [Chrome] shows the prerendered page
                                     no request for the page

Figure 9: the server can tell a speculative request from a real one by Sec-Purpose.

In these runs, the prerender’s subresource requests carried the same Sec-Purpose header as its HTML. So the server can log them apart or skip side effects for them.

The prerender runs used a different profile from the rest of the module. DevTools device emulation didn’t carry over cleanly into the prerendered page. So the window kept its own size, 500 × 813 at a pixel ratio of 1, with Slow 4G and 6x CPU on both pages. Both versions below used that setup, so they compare with each other, not with the earlier numbers.

Figure 10 shows the click with and without the rule. “Map” is the first frame after the seat map’s first render(), from a mark added for these runs only.

after click  0         1         2         3         4
             |         |         |         |         |
no rule      ------------[== JS ==][==== rendering ====] | map 4.24-4.32 s
prerendered  [=====]| map 0.66 s  NEW
late click   [==== the rest of its load ===]| map 3.02-3.14 s

Figure 10: a finished prerender leaves 0.66 s of work after the click; a half-finished one still saves a second.

With the rule, and the click 10 s after the hover, Chrome activated the prerendered page. The map’s first frame came 655 to 665 ms after the click, and LCP was 702 to 715 ms. The only request after the click was the report to /vitals.

The browser still needed about 0.66 s after the click before the first frame, although the seat map’s script had run 9 s earlier.

Pause and predict. A buyer hovers for 1 s and then clicks. The prerender started 0.2 s into the hover and is not finished. Is the click slower than with no rule?

Answer

No, in these runs it was faster. Chrome activated the unfinished prerender at the click, and the page continued its load. The map came 3,017 to 3,138 ms after the click, against 4,239 to 4,316 ms with no rule, because the prerender had a 0.8 s head start.

The prerender’s own HTML request wasn’t slowed by the emulated network in these runs, so the gain may be smaller on a real phone.

The costs of prerendering:

  • Requests for pages nobody opens. Every hover that doesn’t end in a click costs the server the page and its files, and costs the buyer the bytes. Chrome calls this “using up valuable resources of the user for little benefit” when it happens often.
  • Memory and CPU on the phone. A prerendered seat map is 60,000 elements in a hidden tab. Chrome skips speculation when Save-Data is on, with Energy Saver on a low battery, under memory pressure, or when the “Preload pages” setting is off.
  • Analytics runs too. In the prerendered page, the fake analytics.js ran 659 ms into the prerender, 9 s before the click. So a real analytics script would count a page view the buyer may never see. Google Analytics waits for activation by default; others may not. Check document.prerendering or wait for the prerenderingchange event. Module 7 deals with analytics.js.
  • Side effects. A prerender must not do anything a page view would do on the server. TinyTickets doesn’t speculate checkout, because opening it holds seats on the server and sets the hold cookie. MDN lists sign-out, “Add to cart” and one-time sign-in links as unsafe to speculate.
  • Chromium only. Prerender with speculation rules works in Chrome and Edge, and eagerness since 121. Safari 27.3, in beta now, supports prefetch only, and Firefox has prefetch in Nightly (MDN browser compatibility data).

The alternatives, and when the choice flips:

  • Prefetch instead of prerender costs one HTML request and no main-thread work. It fits pages whose wait is mostly the network.
  • conservative waits for the pointer or touch down, so it almost never loads a page for nothing. But it gains only the time between the press and the release.
  • immediate with a URL list is right when the next page is nearly certain, such as the second step of a form. On the show page, it would prerender the map for every visitor.

To confirm a prerender in DevTools, open Application > Background services > Speculative loads and reload the show page. Its Rules view lists the rule, and Speculations shows the seat map as “Ready” after the hover (Chrome for Developers).

A note on the protocol and prerendering

Headless Chrome reported PrerenderingDisabledByDevTools in this course’s research runs. Chromium allows a prerender only when every DevTools session attached to the page uses the tab target, as the DevTools UI does (Chromium source, devtools_instrumentation.cc). So a test script that attaches to the page directly, as the earlier runs did, turns prerendering off. If you test speculation rules with a script, attach through the tab.

Before and after

Figure 11 puts the module’s steps side by side.

What the buyer does Before After Fix
Back from checkout LCP 3,444–3,480 ms, seats lost LCP 28–35 ms, seats kept 1: no no-store, refresh on pageshow
Opens the seat map again later LCP 4,148–4,688 ms, 36 KB LCP 1,224–1,232 ms, 1.6 KB 2: cache headers and ETag
Taps Buy tickets after a hover (different window) map 4.24–4.32 s map 0.66 s 3: prerender with moderate

Figure 11: each kind of second view got its own fix.

None of these fixes changed CLS or the first load of the seat map. The picture still has no width or height (Module 6), analytics.js still blocks the first paint (Module 7), and render() still touches all 60,000 seats (Module 5).

Confirming it in the field

Maya shipped Fixes 1 and 2 together. A week later, the seat map’s Back and Forward lines on phones split in two. Of them, 2,020 had back-forward-cache, with a 75th percentile LCP of 0.1 s.

The other 290 still had back-forward, at 3.8 s. They came from buyers who stayed on checkout longer than 10 minutes, or whose phones dropped the page.

CrUX reports the same split in its navigation_types metric, as the share of page loads per type, including back_forward_cache and prerender (Chrome for Developers). Its 28-day window had not passed the release yet, so Maya kept checking it.

After Fix 3, 26% of the seat map’s loads from phones that came from a show page had prerender, with a 75th percentile LCP of 0.9 s. Her server log showed 2.4 prerender requests for each prerender a buyer used. She decided the extra requests were worth it for the map, and kept the rule off every other link.

In Firefox and Safari

  • Back/forward cache: both have one. Firefox doesn’t store pages with an unload listener; Safari stores them and doesn’t run the handler (web.dev). no-store pages may not be stored in either, so check in each browser.
  • notRestoredReasons is Chrome-only. In Firefox and Safari, count pageshow events with persisted: true instead.
  • immutable works in Firefox and Safari, not in Chrome. stale-while-revalidate works in all three.
  • Speculation rules: prerender is Chromium-only. Safari 27.3 (in beta) supports prefetch, and Firefox Nightly supports prefetch with list rules.

What changed recently

  • Chrome 86 (2020) and Firefox 85 (2021): partitioned HTTP caches; a shared CDN copy is no longer shared between sites.
  • Chrome 123 (2024): notRestoredReasons, fully available from Chrome 125.
  • March and April 2025: Chrome finished rolling out the back/forward cache for no-store pages, after experiments from Chrome 116 (Chrome for Developers).
  • Chrome 149 (June 2026): an open WebSocket no longer blocks the back/forward cache; Chrome closes it when it stores the page (release notes).
  • Chrome 155 (October 2026): the unload deprecation reached 100% of page loads; unload handlers no longer run unless a site opts back in with a Permissions-Policy (Chrome for Developers, updated 2026-10-16).
  • August 2025 and January 2026: on phones, Chrome’s moderate uses viewport heuristics since August 2025. Its eager triggers 50 ms after a link enters the viewport since January 2026 (Chrome for Developers).

Online tools for this step

The back/forward cache tester in DevTools (Application > Background services > Back/forward cache) leaves the page and comes back, then lists what blocked the restore, grouped by whether you can fix it.

  • Data: lab, on your own machine, in Chrome or Edge.
  • Limit: it tests one trip to chrome://terms/, not your real next page. So a blocker that depends on that page, such as a cookie set by checkout, may not appear. A fresh or automated profile may also lack rollouts that users have (step 6 above).
  • When to use something else: for what buyers get, count pageshow with persisted, read notRestoredReasons in the field, or read CrUX navigation_types.

REDbot fetches one URL and checks its headers: caching, ETag and Last-Modified validation, compression and header syntax (about). It explains in words how a cache will treat the response.

  • Data: neither lab nor field; one request from REDbot’s server, with no browser cache.
  • Limit: the public site asks you to pass a human check, doesn’t allow automated queries, and logs every request. A CDN may answer REDbot differently from a buyer’s phone. It’s open source under the MIT license, and you can run it on your own machine to check localhost (source).
  • When DevTools is better: to see what the browser stored and reused, which REDbot cannot see. Never paste a private or internal URL into the public site.

Check yourself

Debugging scenario

A festival organizer’s page on TinyTickets shows ticket prices that change during a sale. Buyers open a ticket’s details page, then press Back. In Chrome, the festival page loads again every time. You find:

  • The festival page is sent with Cache-Control: no-store, “so prices are never old”.
  • While it is open, it calls fetch('/api/prices') every 30 s. The responses also have Cache-Control: no-store.
  • The details page sets no cookie. No WebSocket is open.
  • After Back, the Console snippet prints:
type: back_forward, notRestoredReasons: [{"reason":"masked"},{"reason":"response-cache-control-no-store"},{"reason":"response-cache-control-no-store-with-js-network-request"}]

Why doesn’t Chrome restore the page, and what would you change? The output above is from a lab copy of the seat map built the same way: no-store HTML, one no-store fetch, no cookie change.

Hint 1

Chrome stores no-store pages since 2025, with conditions. Which condition does this page meet, if no cookie changes?

Hint 2

Look at what the page’s own fetch() calls get back.

Answer

Chrome drops a no-store page when the page makes a fetch() or XHR request whose response is also no-store. The price poll does that every 30 s, so the page is never kept, and the third reason names it. masked is a reason Chrome doesn’t explain to the page. In the lab copy, the protocol also listed BrowsingInstanceNotSwapped, a reason about the browser’s processes rather than the page.

Send the festival page’s HTML with no-cache and an ETag instead of no-store, and keep no-store on /api/prices. Add a pageshow handler that fetches the prices again when event.persisted is true. Then test by going to the details page and pressing Back: the snippet should print notRestoredReasons: null, and a pageshow listener should see persisted: true.

Review questions

  1. A stylesheet has no Cache-Control and a Last-Modified date 30 days before it was downloaded. Does Chrome ask the server before it reuses the file the next day?
  2. Which Cache-Control would you send with the HTML, with seats.3f9a1c.js, and with an unversioned styles.css, and why?
  3. After a Back that the back/forward cache did not restore, every file but the HTML came from the cache. Why did the seat map still take 3.4 s?
  4. Why is a pageshow handler that checks persisted better than no-store for keeping seat data current? Where in field data do you see that it works?
  5. Why does TinyTickets prerender the seat map from the show page, but speculate nothing from the seat map to checkout?
Answers
  1. No. Its heuristic freshness is 10% of 30 days, 3 days, so the file is fresh and is reused with no request.
  2. The HTML gets no-cache with an ETag: it’s stored and revalidated on each use, so a new deploy shows at once. seats.3f9a1c.js gets max-age=31536000, immutable, because a change gives it a new name. styles.css gets no-cache with an ETag, because it can change under the same name; the cost is a 304 round trip per visit.
  3. Because the HTTP cache keeps only responses. The page’s JavaScript had to build 60,000 seats again, and the browser had to style, lay out and paint them, about 2.8 s of main-thread work on the phone profile.
  4. no-store throws the whole page away to keep one piece of data current, and in Chrome it drops the page only in some cases anyway. A pageshow handler keeps the page and fetches only what may have changed, about 0.57 s later on the phone profile. In field data, Back and Forward loads report navigationType back-forward-cache instead of back-forward, and CrUX’s navigation_types shows a back_forward_cache share.
  5. Opening checkout holds seats and sets a cookie, a change on the server that a speculative load must not make. The seat map has no side effects and has the longest wait, so prerendering it saves the most.

Lab: keep the page, cache the files, start the next one

Time: about 15 minutes. You need the lab app from Module 3, Chrome and Node.js. The finished code for this module is in the course repository, folder module-04/.

  1. Add checkout.html, checkout.js and payment.js, the checkout link in seats.html and seats.js, and the two headers in server.js, from “Build checkout”. Run node server.js. In Chrome, set the phone profile with Disable cache unchecked, and turn on Preserve log in the Network panel.
  2. Open the seat map, pick two seats, continue to checkout, and press Back. Predict what the Network panel will show, then check. Paste the Console snippet.
  3. Run the back/forward cache tester on the seat map. Compare its result with what happened on the real Back in step 2.
  4. Apply Fix 1. Restart the server, repeat step 2, and compare the snippet’s output and the picked seats.
  5. Apply Fix 2. Open the seat map, open the show page, then type the seat map’s address again. In the Network panel, read the Status and Size columns. Record the page in the Performance panel and read Use efficient cache lifetimes in the Insights tab.
  6. Apply Fix 3. Open Application > Background services > Speculative loads, reload the show page, and hold the pointer over Buy tickets. Watch the seat map change to “Ready”, then click. Run this in the Console of the seat map:
const nav = performance.getEntriesByType('navigation')[0];
console.log(`activationStart: ${Math.round(nav.activationStart)} ms`);

A value above 0 means the page was prerendered.

Results from one run

These come from headed Chrome 157 on a 2019 laptop (Intel Core i7-9750H) through the DevTools Protocol, not from the DevTools UI. Your numbers will differ.

  • Step 2: only seats.html went to the network (200, 1,335 bytes). LCP after Back was 3,480 ms, with navigationType back-forward. The snippet printed type: back_forward, notRestoredReasons: [{"reason":"response-cache-control-no-store"}] and seats picked: 0.
  • Step 3: not run in the DevTools UI. The protocol event behind it named CacheControlNoStoreCookieModified for the real Back.
  • Step 4: restored in 32 ms, with no request for the page and one for /api/sold. The snippet printed type: navigate, notRestoredReasons: null and seats picked: 2.
  • Step 5: six 304 responses and the picture from the cache; FCP and LCP 1,228 ms. The cache insight failed before the fix (six files, lifetime 0 s) and passed after.
  • Step 6: in the 500 × 813 window, the seat map was prerendered on hover and shown with an LCP of 728 ms after the click.

Stretch: use "eagerness": "conservative" instead of moderate. Compare the time from the click to the map, and count the prerenders in the Speculative loads panel while you move the pointer over the page.

Cheat sheet

The second visit and the next click
  1. Fresh: no request. Stale with a validator: 304. No validator: 200.
  2. No Cache-Control is not "no cache": Chrome uses 10% of Last-Modified's age
  3. no-cache = store and revalidate; no-store = keep nothing
  4. Back reuses stale cached files; the main thread still rebuilds the page
  5. bfcache keeps the whole page; refresh data in pageshow when persisted
  6. Test Back from the real next page; read notRestoredReasons in the field
  7. Immutable only for versioned URLs; the HTML stays no-cache + ETag
  8. Prefetch saves the HTML; prerender also saves the main thread
  9. Speculate only pages without side effects; check Sec-Purpose and analytics

Figure 12 is the whole module in one picture: three ways a second view reuses earlier work, and what each one still costs.

             what is reused          what still runs             fix in lab
             --------------------    -------------------------   -----------
HTTP cache   responses               HTML request (304),         2: headers,
                                     JS, style, layout, paint       ETag
bfcache      the whole page          a pageshow refresh          1: no
                                                                    no-store
prerender    the page, loaded        about 0.66 s after          3: moderate
             before the click        the click                      rule

Figure 12: the more a store keeps, the less the main thread repeats.

Next, in Module 5, a buyer taps one seat on the 60,000-seat map, and the seat turns orange about a second later. Maya reads the three parts of INP and breaks up render().

Sources