The back/forward cache
Make Back and Forward instant: how Chrome's back/forward cache keeps a page, what keeps it out, NotRestoredReasons, and measuring your hit rate.
- 01Follow a page into the cache and outRead pagehide, freeze, resume and pageshow, and know how long Chrome keeps a page and how many it keeps.
- 02Find what keeps a page out, and fix itSpot unload listeners, no-store pages whose cookies change and messages that push a page out, with DevTools and NotRestoredReasons.
- 03Measure your hit rateCount restores against every trip back, from your own pages or from Chrome's field data.
Back, at once or from the start
Welcome to Stage 10, Instant navigations. So far, the course has made each page faster on its own: to load, to respond and to stay still. This stage makes the next page appear at once. There are three ways to do that:
- keep the page the visitor just left, so Back can show it again;
- fetch or build the next page before the visitor asks for it;
- in a single-page app, change the view without loading a new page.
This module covers the first two. This lesson starts with the Back button.
Asha is reading the mint tea reviews on Ravi's Leaf and Kettle site, the page from lesson 32.3. She taps Helpful under Ravi's review, and the button turns green. Then she taps Mint tea in the shop, to check the price. She presses Back. The reviews are there at once, and Ravi's Helpful button is still green.
The next day she does the same, with one change. On the Mint tea page, she taps Add to cart first. Then she presses Back. This time the Mint tea page stays on screen for a moment. Then the reviews appear, and the Helpful button is white again. Her tap is gone.
Same page, same Back button. Why did one trip back take no time at all, while the other started the page over? Here is what Chrome showed, in real frames:
Here are the two times as code:
// Asha pressed Back. When were the reviews on screen again, in ms after Back?// The middle of 5 tries each, read from Chrome's own screenshots.const justLooked = { onScreen: 2.3, helpfulLit: true };const addedToCart = { onScreen: 304.8, helpfulLit: false }; const say = (trip) => `on screen in ${trip.onScreen} ms, Helpful ${trip.helpfulLit ? "still lit" : "not lit"}`;console.log(`Just looked: ${say(justLooked)}.`);console.log(`Added to cart: ${say(addedToCart)}.`);- Lines 1 and 2 are comments. A millisecond (ms) is a thousandth of a second. The course pressed Back 5 times for each trip, in Chrome 157, on a phone-sized screen. The CPU ran 4 times slower and the network was DevTools' Fast 4G, as on Asha's phone.
- Line 3 is the trip where Asha only looked. The reviews were back on screen 2.3 ms after Back, with the Helpful button still lit.
- Line 4 is the trip after Add to cart: 304.8 ms, and the button wasn't lit.
- Lines 6 to 8 print
Just looked: on screen in 2.3 ms, Helpful still lit.andAdded to cart: on screen in 304.8 ms, Helpful not lit.
2.3 ms is far less than one frame on a 60 Hz screen, which lasts 16.7 ms. So the first time, Chrome didn't load the reviews at all. It had kept the whole page, Asha's tap included, and simply showed it again. The second time, it had thrown that page away. So Back loaded the reviews from the start: a new request, new HTML and new scripts.
The place Chrome kept the page is the back/forward cache, or bfcache. It keeps a page you leave whole in memory: its elements, its styles, and its JavaScript, paused. Lesson 15.3, The browser's caches, compared it to pausing a film. Press Back or Forward, and the browser shows the kept page instead of loading it.
You're halfway through a board game when dinner is ready. You leave the board on the table, every piece where it was. After dinner you sit down and carry on from the same move. If someone had packed the game away, you'd set it all up again. And nobody would remember whose turn it was.
- In real life: The board, left on the table
- In JavaScript: The page, kept whole in the back/forward cache
- In real life: Every piece where it was
- In JavaScript: The page's elements and JavaScript, Ravi's green button included
- In real life: Carrying on after dinner
- In JavaScript: Back: Chrome shows the kept page, 2.3 ms later
- In real life: Setting it all up again from the box
- In JavaScript: A full load: request, HTML and scripts, 304.8 ms
When you leave a page, the browser may keep the whole page, paused, in memory. Press Back, and it shows that page again instead of loading it. Some things a page does make the browser throw the kept page away. Then Back loads the page from the start.
The rest of this lesson goes step by step. First, how Chrome keeps a page, and what keeps a page out. Then the end of the unload event, and pages sent with no-store. Last, how to ask Chrome why, and how to count how often it works.
What Chrome keeps, and for how long
Let's follow Asha's first trip, the one on the left of the picture. The course added a small script that noted every event Ravi's page heard. It isn't part of Ravi's page.
// What Ravi's page heard in one recorded trip.// Leaving is timed from pagehide. Coming back is timed from Back.const leaving = { pagehide: 0, freeze: 11.3 };const comingBack = { resume: 6.3, pageshow: 6.5 };const timerRuns = 0; // a 100 ms timer, while the page was away for 2,024 ms console.log(`Leaving: pagehide, then freeze ${leaving.freeze} ms later.`);console.log(`Coming back: resume at ${comingBack.resume} ms, pageshow at ${comingBack.pageshow} ms.`);console.log(`The timer ran ${timerRuns} times while the page was away.`);- Line 3 is leaving. The page heard
pagehide, and thenfreeze11.3 ms later. - Line 4 is coming back. It heard
resume6.3 ms after Back, andpageshowat 6.5 ms. - Line 5 is a timer the script set to run every 100 ms. In the 2,024 ms the page was away, it ran 0 times.
- Lines 7 to 9 print
Leaving: pagehide, then freeze 11.3 ms later.,Coming back: resume at 6.3 ms, pageshow at 6.5 ms.andThe timer ran 0 times while the page was away.
Put together, here is the trip, step by step:
- Asha taps the link. Chrome checks Ravi's page against its list of things that keep a page out. Nothing does.
- Chrome fires
pagehidewithpersistedset to true. It means "this page may be kept". The page is now hidden. - Chrome freezes the page: its timers and its scripts stop. Lesson 29.1 met frozen tabs. A frozen page keeps its memory, but runs no code. That's why the timer never ran.
- Asha presses Back. Chrome takes the page out of the cache and shows it. Its first frame came 2.3 ms after Back.
- The page wakes up. It hears
resume, thenpageshowwithpersistedset to true. Its timers carry on.
pagehide says the page may be kept, then Chrome freezes it. On Back, resume comes first, then pageshow, 6.5 ms after Back.Then the Mint tea page went into the cache in its turn, ready for the Forward button. The HTML standard describes all this with one flag. Every page starts out salvageable, a word for "can be saved". As the page is left, the browser decides whether to keep it. If not, the flag turns false. The persisted on pagehide is that flag. And the standard fires unload only when the flag is false: only for a page that won't come back.
A kept page doesn't wait forever. In Chrome 157's own code:
- A page waits 10 minutes at most. Then Chrome throws it away.
- Each tab keeps 6 pages at most. A seventh pushes the oldest out.
- When the device runs low on memory, Chrome keeps fewer. When it runs very low, it keeps none.
- A page sent with
no-storewaits 3 minutes at most. More on that below.
Why it matters: the cache is for the quick trip back, which is the one people make most. A visitor who comes back after lunch gets a full load.
Try it on this very page. The link opens a plain page on this site. Press your browser's Back button to come back, and read what happened:
// What this lab runs while you read.addEventListener("pageshow", (event) => { if (event.persisted) restores += 1;}); const [visit] = performance.getEntriesByType("navigation");const type = visit.type;const reasons = visit.notRestoredReasons?.reasons.map((item) => item.reason);0……Reading this page's navigation entry.
Lines 2 and 3 of the lab's code count each pageshow whose persisted is true. If this page comes back from the cache, the count goes up, because the lab's script never stopped. If it loads again, the count starts from 0, and the lab reads the reasons instead.
What keeps a page out
Not every page can be kept. Chrome checks at two moments:
- As the visitor leaves, it looks at what the page is doing. Some things keep the page out at once.
- While the page waits, some events throw it out. Browsers call that eviction.
Why would a page be refused? A frozen page can't answer anyone. If it holds something that other pages or the server rely on, they could get stuck waiting for it. So the browser keeps such a page out, or lets it go the moment it's needed. It's like a book on a library's hold shelf: it waits for you, unless someone else needs it first.
Live connections are the classic case. Ravi added live reviews to his page: a WebSocket, a line to the server that stays open while the page does. Older versions of Chrome kept such pages out. Chrome 157 keeps the page and fails the socket as the page is frozen, with the message "Page entered Back-Forward Cache." In the recording, all 5 trips back were restored. In all 5, the page came back with its socket closed. So the live reviews stopped. The page has to open a new socket on pageshow. Exercise 4 asks you to write that.
Ravi's pages can also talk to each other on a BroadcastChannel, a named channel that every open page of a site can send messages on. An open channel doesn't keep a page out. But if a message arrives while the page waits, Chrome throws the page out, because a frozen page can't hear it.
Read this table across: each row is something a page does, what Chrome does with it, and what to do instead.
| What the page does | What happens | What to do |
|---|---|---|
An unload listener | Firefox keeps the page out. So does a Chrome where unload still runs. | Send reports on pagehide, and send Permissions-Policy: unload=(). |
Sent with Cache-Control: no-store | Kept for 3 minutes at most, and thrown out if a cookie changes. | Send no-cache unless the page is private. |
| An open WebSocket | Kept, but Chrome closes the socket. | Open a new socket on pageshow. |
| A BroadcastChannel message while it waits | Thrown out. | Close the channel on pagehide, and open it again on pageshow. |
Another window holds it through window.opener | Kept out. | Open links with rel="noopener". |
Chrome has a longer list, for rare features such as video calls and Bluetooth. You don't need to learn it. Chrome's DevTools can tell you which items your page hits. Open the Application panel, find Back/forward cache under Background services, and press Test back/forward cache. Chrome visits chrome://terms and comes back. If your page wasn't restored, DevTools lists the reasons in three groups:
- Actionable: you can fix these in your page.
- Pending Support: Chrome doesn't support these yet. They'll stop blocking once it does.
- Not Actionable: something outside the page caused them.
The course's recorder read the same reasons through DevTools' protocol, for every trip back. Here are six versions of Ravi's page. Pick one to see what happened:
Cache-Control: no-store
Extra code: none
On the Mint tea page: Asha taps Add to cart0 of 5305.4 ms304.8 ms0 of 5the network (11,428 bytes)CacheControlNoStoreCookieModified (Actionable)response-cache-control-no-storeRestored 0 of 5 times. Add to cart set a cookie while the no-store page waited, so Chrome threw the page out. Back fetched it again from the server.
Why it matters: one small feature can cost every visitor the instant Back. Run the DevTools test after you add a script, a socket or a channel.
The end of the unload event
Lesson 5.1 called unload the old page's last chance to run code. Lessons 12.3 and 15.3 found that it costs the back/forward cache. Now you can see why.
The standard fires unload only for a page that won't be kept. So a page with an unload listener forces the browser to choose. It can keep the page and skip the listener. Or it can run the listener and throw the page away. Firefox on desktop throws the page away. Safari keeps some pages and skips the listener.
When you move out of a flat, you follow a checklist: hand back the keys, switch off the gas, read the meter. When you step out for a coffee, you don't. Now imagine a checklist that says "do this every time I leave". Either you ignore it on coffee trips, or you move out every time you go for a coffee.
- In real life: Moving out of the flat
- In JavaScript: The page is thrown away
- In real life: The moving-out checklist
- In JavaScript: An unload listener
- In real life: Stepping out for a coffee
- In JavaScript: The page goes into the back/forward cache
- In real life: A note you leave every time you go out
- In JavaScript: A pagehide listener: it runs either way
Ravi's old analytics script still had a moving-out checklist:
// Ravi's old analytics: report the visit as the page goes away.addEventListener("unload", () => { navigator.sendBeacon("/visit", "reviews");});- Line 1 is a comment.
- Line 2 adds a listener for
unload. - Line 3 sends a small report with
navigator.sendBeacon(), the way lesson 12.3 sent its reports.
The course recorded the same page twice: as it is, and with one extra response header. Here are both:
// Back to Ravi's page with the unload listener, 5 times each, in the course's Chrome.// How many were restored, the middle time to pageshow in ms, and how many reports arrived.const listener = { restored: 0, ms: 131.5, reportArrived: 5 };const withHeader = { restored: 5, ms: 6.7, reportArrived: 0 }; console.log(`unload listener: restored ${listener.restored} of 5, ${listener.ms} ms, ${listener.reportArrived} reports.`);console.log(`With the header: restored ${withHeader.restored} of 5, ${withHeader.ms} ms, ${withHeader.reportArrived} reports.`);- Line 3 is the page as it is: restored 0 times, 131.5 ms to
pageshow, and all 5 reports arrived. - Line 4 is the same page with the header: restored 5 times, 6.7 ms, and no report at all.
- Lines 6 and 7 print
unload listener: restored 0 of 5, 131.5 ms, 5 reports.andWith the header: restored 5 of 5, 6.7 ms, 0 reports.
Without the header, the listener ran each time Asha left, and Chrome kept the page out. Back loaded it again from the HTTP cache, with no request to the server. Even so, it took about 20 times as long as the restore on line 4.
But wait. Chrome's guide says the deprecation is complete: from Chrome 155, "The unload event will no longer fire by default". So why did it fire here? In Chrome 157's code, that change is a switch, and the switch is off. Chrome turns it on for its users with a field trial: a setting Google sends to Chrome browsers from its servers. The course's Chrome started with a new profile and had no such settings. So unload still ran. The same goes for lesson 12.3's Chrome, where the unload report still arrived.
And what does the switch do? It makes every page behave as if it had sent this header:
Permissions-Policy: unload=()Permissions-Policy is a response header that turns browser features on or off for a page. unload=() means "allow unload listeners for no one", third-party scripts included. When a script then asks for one, Chrome doesn't add it. That's line 4 of the example above: no listener, so no report, and every trip back restored.
Why it matters: in Chrome today, an unload listener usually doesn't run at all. In Firefox it keeps your page out of the cache. Either way, it lets you down. Send your reports on pagehide instead:
// Ravi's analytics, fixed: report the visit when the page is hidden.addEventListener("pagehide", () => { navigator.sendBeacon("/visit", "reviews");});- Line 2 listens for
pagehide. It fires whenever the page is left, whether it's kept or not. - Line 3 sends the same report as before. The page can still go into the cache.
Pages sent with Cache-Control: no-store
Lesson 15.1 met Cache-Control: no-store. It tells every cache never to keep a copy. Sites send it with private pages, such as an account page. For years, browsers kept no-store pages out of the back/forward cache too.
Chrome changed that. In Chrome 157's code, a no-store page can go into the cache, with three rules:
- It waits 3 minutes at most, not 10.
- If any of the page's cookies changes while it waits, Chrome throws it out.
- If it ever opened a WebSocket, a WebRTC call or a WebTransport connection, it's kept out, even if it closed them.
Cookies are the clue. Most sites keep who you are in a cookie. When you sign out, the cookie changes. A private page from before must not come back on Back.
You step away from an office front desk and leave your private folder there. The receptionist keeps it for you, but only for a few minutes, and only while your visitor badge stays the same. Come back with a new badge, and the folder goes in the shredder. They fetch you a fresh copy instead.
- In real life: Your private folder, left at the desk
- In JavaScript: A no-store page in the back/forward cache
- In real life: A few minutes at most
- In JavaScript: 3 minutes
- In real life: Your visitor badge
- In JavaScript: The page's cookies
- In real life: A new badge, so the folder is shredded
- In JavaScript: A cookie changed, so the page is thrown out
- In real life: A fresh copy fetched for you
- In JavaScript: Back loads the page from the server
That's the whole story of the opening. Ravi sends his reviews with no-store, so they're always fresh. And Ravi's shop keeps Asha's cart in a cookie, set when she taps Add to cart. The course made three trips:
// Back to Ravi's reviews, 5 times each.// How many were restored, and the middle time to pageshow, in ms.const trips = [ ["no-store, Asha only looks", 5, 7.2], ["no-store, Asha adds to her cart", 0, 305.4], ["no-cache, Asha adds to her cart", 5, 7.6],];for (const [page, restored, ms] of trips) console.log(`${page}: restored ${restored} of 5, ${ms} ms`);- Lines 4 and 5 are the opening's two trips. The page is the same. Only the cart cookie differs.
- Line 6 is the same trip as line 5, with the reviews sent with
no-cacheinstead. - Line 7 prints one line per trip. The first is
no-store, Asha only looks: restored 5 of 5, 7.2 ms. The second isno-store, Asha adds to her cart: restored 0 of 5, 305.4 ms. The third isno-cache, Asha adds to her cart: restored 5 of 5, 7.6 ms.
pageshow.After Add to cart, Chrome threw the page out, so Back asked the server again. The first byte alone took 165.9 ms: DevTools' Fast 4G adds 165 ms of waiting to every request. With no-cache, the same cookie changed, and it didn't matter.
Why it matters: reviews aren't private. no-cache keeps them fresh on every load, and it leaves the back/forward cache alone. Keep no-store for pages that really are private. And remember that a restored page isn't checked with the server. If Ravi's reviews change every minute, he can fetch new ones on pageshow when persisted is true.
Asking why with NotRestoredReasons
DevTools tells you why on your own computer. Your visitors' browsers can tell you too. The navigation entry from lesson 5.1 has a field for it: notRestoredReasons.
When a parcel can't be delivered, it comes back with a sticker: "Address unknown", or "Refused". The sticker doesn't fix anything. But it tells you what to fix. Sometimes it only says "Undeliverable", to keep someone else's details private.
- In real life: The parcel comes back to you
- In JavaScript: Back loads the page again
- In real life: The sticker on it
- In JavaScript: notRestoredReasons
- In real life: "Address unknown"
- In JavaScript: A reason, such as response-cache-control-no-store
- In real life: Only "Undeliverable"
- In JavaScript: masked: there was a reason, but it isn't named
Here is how Ravi's page can read its sticker:
const [visit] = performance.getEntriesByType("navigation");
console.log(visit.type);
console.log(visit.notRestoredReasons);- Line 1 gets the page's navigation entry.
- Line 2 prints its type. After the trip that loaded the reviews again, it printed
back_forward. - Line 3 prints the reasons. In the trip from the picture, Chrome gave this object, with the server's address cut off:
{ "src": null, "id": null, "url": "/v/no-store-cart/", "name": null, "reasons": [ { "reason": "response-cache-control-no-store" } ], "children": []}- Line 4 is the page's address,
url. - Lines 2, 3 and 5 are
src,idandname. They describe an iframe, so they'renullfor the page itself. - Lines 6 to 10 are the
reasons, a list. Each item has onereason. Line 8 says the page was sent withno-store. - Line 11 is
children: one entry for each iframe on the page. Ravi's page has none.
Three things to know before you rely on it:
- It only has reasons after a trip back that loaded the page. On a normal visit it's
null. It's alsonullwhen nothing blocked the page. A restored page gets no new navigation entry at all. So count restores withpageshow, not with this. - Some reasons are
masked, which means "there was a reason, but I won't name it". The standard uses it for iframes from other sites, so one site can't learn about another. Browsers use it for reasons of their own, too. For theunloadversion, Chrome only saidmasked. DevTools named two reasons for the same page, in the playground above. - The names can change between Chrome versions, Chrome's guide warns. Store them as plain text, and count them.
Measuring your hit rate
Your hit rate is the share of trips back and forward that the cache answered. Ravi measures his with a few lines, on every version of the page:
// Ravi's counter: one report each time the reviews are shown.function report(type, reasons) { navigator.sendBeacon("/bfcache-log", JSON.stringify({ type, reasons }));} const [visit] = performance.getEntriesByType("navigation");report(visit.type, visit.notRestoredReasons?.reasons.map((item) => item.reason) ?? null); addEventListener("pageshow", (event) => { if (event.persisted) report("back_forward_cache", null);});- Lines 2 to 4 make a small helper that sends one report with
navigator.sendBeacon(). - Line 6 gets the navigation entry.
- Line 7 sends its type:
navigateon a normal visit,back_forwardwhen Back loaded the page again. The reasons go with it, ornull. - Lines 9 to 11 send
back_forward_cachewhenpageshowhaspersistedset to true. A restored page doesn't run its scripts again, so line 7 can't catch it.
After the course's 35 visits, Ravi's server had 70 reports. Here they are, added up:
// Ravi's counter, after 35 visits: 5 to each of 7 versions of his page.const reports = { navigate: 35, back_forward: 15, back_forward_cache: 20 }; const backs = reports.back_forward + reports.back_forward_cache;const hitRate = Math.round((reports.back_forward_cache / backs) * 100);console.log(`${backs} trips back, ${reports.back_forward_cache} restored: a hit rate of ${hitRate}%.`);- Line 2 holds the recorded counts: 35 normal visits, and 35 trips back. 15 loaded again and 20 were restored.
- Line 4 adds up the trips back. Line 5 divides the restores by them.
- Line 6 prints
35 trips back, 20 restored: a hit rate of 57%.
A café owner wants to know how often returning guests find their table still set. She counts every guest who comes back, and how many found their table waiting. When a table was cleared, she notes why. The notes tell her what to change first.
- In real life: A guest coming back to the café
- In JavaScript: A trip back or forward
- In real life: Finding the table still set
- In JavaScript: A back_forward_cache report
- In real life: Finding it cleared
- In JavaScript: A back_forward report, with its reasons
- In real life: Set tables out of all returns
- In JavaScript: The hit rate
Don't aim for 100%. web.dev lists trips back that no page can control. The visitor quit the browser and started it again, duplicated the tab, or reopened a closed tab. And a page waits 10 minutes at most.
You don't even need your own code to start. Since the March 2024 dataset, Chrome's field data, CrUX, reports navigation_types: the share of page loads of each kind. Two of them are trips back: back_forward_cache for restores, and back_forward for the rest. Divide the first by the two together, and you have your hit rate. The web-vitals library marks each report the same way, with a navigationType of back-forward-cache.
Try it with Ravi's real reports. Switch a version off to see the hit rate without it:
// What the playground adds up, for the versions switched on.
const backs = restored + loadedAgain;
const hitRate = Math.round((restored / backs) * 100);35201557%35 trips back, 20 restored and 15 loaded again. Switch a version off to see the hit rate without it.
Why it matters: the 15 trips that loaded again came from only three versions, and each report said why. A hit rate tells you how much to gain. The reasons tell you where.
Restored, or loaded again?
Each page below has just been left. Sort it by what Chrome does when the visitor presses Back:
- A no-cache page with an open WebSocket
- A no-store page, back after one minute, no cookie changed
- A no-store page whose cart cookie changed while it waited
- A page with an unload listener and Permissions-Policy: unload=()
- A page that gets a BroadcastChannel message while it waits
- A page left 15 minutes ago
- A page that sends its report from a pagehide listener
- A no-store page, back after five minutes
Sort each page by what happens on Back in Chrome.
Common mix-ups
- "The back/forward cache is the HTTP cache." No. The HTTP cache keeps files. The back/forward cache keeps the whole page, running JavaScript included. Back after the
unloadlistener came from the HTTP cache, and still took 131.5 ms. - "A restored page runs its scripts again." No. It carries on where it stopped. Listen for
pageshowto notice the restore. - "no-store always keeps a page out." No. Chrome keeps it for 3 minutes, as long as no cookie changes.
- "An open WebSocket keeps a page out of Chrome's cache." No. Chrome keeps the page and closes the socket. Open a new one on
pageshow. - "A null notRestoredReasons means the page was restored." No. It's also null on a normal visit, and a restored page gets no new entry. Use
persisted. - "unload doesn't matter any more." No. Firefox still keeps such pages out, and Chrome still runs it for sites that opt back in. Use
pagehide.
Practice exercises
Answer first, then use the hints.
Ravi switches his reviews from no-store to no-cache. What does the last line print now?
// The same 35 visits, after Ravi sends his no-store page with no-cache.
const reports = { navigate: 35, back_forward: 10, back_forward_cache: 25 };
const backs = reports.back_forward + reports.back_forward_cache;
const hitRate = Math.round((reports.back_forward_cache / backs) * 100);
console.log(`${backs} trips back, ${reports.back_forward_cache} restored: a hit rate of ${hitRate}%.`);35 trips back, 25 restored: a hit rate of 71%. One header change moves 5 trips from loading again to restored.
Asha opens the reviews, follows the link to the Mint tea page, and presses Back. The reviews are restored. How many reports does Ravi's counter send in all?
2: navigate from the first load, then back_forward_cache from pageshow after the restore. The first load's pageshow has persisted set to false, so it sends nothing.
In the six trips playground, how many bytes came over the network when Back loaded the no-store page again after Add to cart?
11,428 bytes, from the network. The no-store page had no copy in the HTTP cache, so Back fetched all of it again. The unload version came from the HTTP cache: 0 bytes.
Ravi's live reviews stop after Asha comes back from the cache. Rewrite his WebSocket code so it opens a new socket after a restore. Which event do you listen for?
// Live reviews that keep working after a trip to the cache.
function connect() {
const socket = new WebSocket(`wss://${location.host}/live`);
socket.addEventListener("message", (event) => showReview(event.data));
return socket;
}
let live = connect();
addEventListener("pageshow", (event) => {
if (event.persisted && live.readyState === WebSocket.CLOSED) live = connect();
});Opening the socket moves into a function, so the page can call it again. On pageshow, if the page was restored and its socket is closed, it opens a new one. A page that never went into the cache keeps its first socket.
Open this copy of Ravi's page in Chrome, version 125 or later. Follow Mint tea in the shop, tap Add to cart, and press Back. Then open DevTools' Console and run performance.getEntriesByType("navigation")[0].notRestoredReasons.reasons. Which reason does it give?
performance.getEntriesByType("navigation")[0].notRestoredReasons.reasonsbroadcastchannel-message: the message reached the page while it waited in the cache, so Chrome threw it out. The course's recorder got the same reason in all 5 trips.
Ravi's account page is sent with no-store. Asha opens it, follows a link to Sign out, and the server clears her session cookie. A minute later she presses Back. Is the account page restored, or loaded again?
Loaded again. The account page was sent with no-store, and signing out changed a cookie while it waited, so Chrome threw it out. That's exactly why the rule exists: after signing out, Back must not show a private page.
Check your understanding
For each question, ask whether the page was kept, and if not, what threw it out.
Question 1 of 7What does the first line of the opening example print?
Read the code, then predict// Asha pressed Back. When were the reviews on screen again, in ms after Back? // The middle of 5 tries each, read from Chrome's own screenshots. const justLooked = { onScreen: 2.3, helpfulLit: true }; const addedToCart = { onScreen: 304.8, helpfulLit: false }; const say = (trip) => `on screen in ${trip.onScreen} ms, Helpful ${trip.helpfulLit ? "still lit" : "not lit"}`; console.log(`Just looked: ${say(justLooked)}.`); console.log(`Added to cart: ${say(addedToCart)}.`);Choose an answer to see the explanation.
Question 2 of 7While Ravi's page waited in the cache, how many times did its timer run?
Choose an answer to see the explanation.
Question 3 of 7In the recorded trip, which event did the restored page hear first?
Choose an answer to see the explanation.
Question 4 of 7Ravi sends Permissions-Policy: unload=() with a page that adds an unload listener. What happens?
Choose an answer to see the explanation.
Question 5 of 7A page sent with no-store waits in Chrome's cache. While the visitor is away, a script sets a cookie. What happens on Back?
Choose an answer to see the explanation.
Question 6 of 7When is notRestoredReasons null?
Choose an answer to see the explanation.
Question 7 of 7Ravi's counter sends back_forward and back_forward_cache reports. Which share is his hit rate?
Choose an answer to see the explanation.
Key takeaways
- The back/forward cache keeps a page you leave whole and frozen. Back shows it again in a frame, with its state.
pagehideandpageshowcarrypersisted. A restored page hearsresume, thenpageshow.- Chrome keeps a page 10 minutes at most, and 6 pages per tab. A no-store page waits 3 minutes, and leaves when a cookie changes.
- Don't use
unload. SendPermissions-Policy: unload=(), and report onpagehide. - DevTools' test and
notRestoredReasonssay why a page was loaded again. The hit rate says how often.
Remember the one-liner.
Leave the board set up: a kept page comes back in a frame, and every blocker you remove makes Back instant for more visitors.
Sources
The facts on this page come from these specs, docs and source files:
- Back/forward cache, web.dev.
- HTML Standard: unloading documents (salvageable, pagehide and unload), WHATWG.
- back_forward_cache_impl.cc, lines 78 to 122: six pages per tab, ten minutes each, Chromium source.
- dom_websocket.cc, lines 602 to 627: a WebSocket fails when its page is frozen for the cache, Chromium source.
- broadcast_channel.cc, lines 192 to 203: a message pushes a cached page out, Chromium source.
- Test back/forward cache, Chrome DevTools docs.
- Deprecating the unload event, Chrome for Developers.
- features.cc, lines 357 to 359: the unload deprecation's switch, off by default, Chromium source.
- back_forward_cache_impl.cc, lines 1160 to 1169: an unload listener keeps a page out, Chromium source.
- event_target.cc, lines 631 to 640: Permissions-Policy unload stops the listener being added, Chromium source.
- Back/forward cache for Cache-Control: no-store pages, Chrome for Developers.
- content_features.cc, lines 231 to 236: no-store pages may enter the cache, Chromium source.
- back_forward_cache_impl.cc, lines 433 to 454: restore unless cookies change, three minutes, Chromium source.
- HTML Standard: the NotRestoredReasons interface, WHATWG.
- Back/forward cache notRestoredReasons API, Chrome for Developers.
- back_forward_cache_can_store_document_result.cc, lines 508 to 640: Chrome's reason names, and masked, Chromium source.
- PerformanceNavigationTiming: notRestoredReasons, MDN.
- Navigation types in CrUX, Chrome for Developers.
Coming next: Speculation Rules. Back is covered. Next, you'll make the next page appear at once, by fetching or building it before the visitor clicks.