completefrontend
Open lab My progress
THE WEB PERFORMANCE FIELD GUIDE

Fast route changes

Make route changes in a single-page app fast: load the code and data together and early, draw the new view at once, restore the scroll, and keep memory level.

By the end, you can
  • 01
    Load a route earlyStart a route's code and its data together, and before the tap when you can, so neither waits for the other.
  • 02
    Answer every tap at onceDraw the new view's frame in the same click, so the next paint shows that the tap worked.
  • 03
    Keep the place and the memoryPut the list back where it was on Back, and clean up each view as it leaves, so long visits stay fast.

No new page, but still a wait

Ravi has turned his Leaf and Kettle shop into a single-page app. The browser loads one page, shop.html, once. After that, his JavaScript changes what the page shows. The list of eight teas is one screen. Each tea's page is another. Each screen is called a route, and moving from one to another is a route change.

Ravi expected route changes to be instant. There's no new page to load, after all. Then Asha taps Mint tea. Nothing happens. The list just sits there. More than half a second later, the whole tea page appears at once.

Why did she wait, if no new page loaded? Ravi built a second version of his app too. Here are both taps, frame by frame:

Asha taps Mint tea in Ravi's single-page app twice, in real frames from Chrome. Code, then data, after the tap: the list stays on screen until the tea page appears at 613.5 ms. Code and data started on hover: the list stays on screen until the tea page appears at 136.5 ms. Beside each row, a bar drawn to scale from the tap to the tea page.Code, then data, after the tapRavi's list at the tap: Our teas, with Mint tea's photo, name and price at the top.613.5 ms after the tap: the Mint tea page, with its photo, name, price, Add to cart button and a link back to the teas.the tap613.5 ms613.5 msCode and data started on hoverRavi's list at the tap: Our teas, with Mint tea's photo, name and price at the top.136.5 ms after the tap: the Mint tea page, with its photo, name, price, Add to cart button and a link back to the teas.the tap136.5 ms136.5 msthe list, still on screen after the tap
Real frames from Chrome, the middle of 5 taps each. Nothing on the screen moved until the whole tea page was ready.

Here are the two taps as code:

Asha's two taps on Mint teaPop out in the code editor (opens in a new tab)JavaScript
// Asha taps Mint tea. When was its page on screen, in ms after the tap?// The middle of 5 taps each, from Chrome's own screenshots.const codeThenData = 613.5;const startedOnHover = 136.5; console.log(`Code, then data: ${codeThenData} ms`);console.log(`Started on hover: ${startedOnHover} ms`);console.log(`Saved: ${(codeThenData - startedOnHover).toFixed(1)} ms`);
  • Lines 1 and 2 are comments. The course tapped each version 5 times. These are the middle taps, timed from Chrome's own screenshots.
  • Line 3 is Ravi's first version. Line 4 is his second. It starts loading when the pointer comes onto a tea.
  • Lines 6 to 8 print Code, then data: 613.5 ms, Started on hover: 136.5 ms and Saved: 477.0 ms.

So the wait was real, and most of it could go. Where did it come from? A tea page needs two things the list doesn't have. It needs its code: the JavaScript that draws a tea page. And it needs its data: the tea's name, price and words. Both live on Ravi's server. Both have to travel to Asha.

Real-life analogyStaying in the shop doesn't bring the stockroom closer

You walk into a tea shop and ask for a tin of mint tea. You don't leave the shop. You don't queue again at the door. But the tins are in the stockroom, so the assistant still walks there and back. If she first fetches the order book, and only then goes back for the tin, you wait for two walks.

In real life: Staying in the shop
In JavaScript: No new page: the app stays on shop.html
In real life: A walk to the stockroom
In JavaScript: A request to Ravi's server
In real life: Fetching the order book, then the tin
In JavaScript: Loading the code, then the data
In real life: The tin on the counter
In JavaScript: The tea page on screen
The main idea

A route change is a small page load inside one page. The new view still needs its code and its data from the server. So start both together, and early. Draw something at once. Put the scroll back where it was. And clean up what the old view leaves behind.

Those are this lesson's four jobs, one section each. For how single-page apps differ from sites that load a new page each time, see Single-page vs multi-page apps.

How the course recorded it

  • Ravi's app: shop.html, its main script app.js, and a separate file of code for tea pages, tea-page.js. The list shows eight teas, each with a photo. A tea page lives at an address like shop.html?tea=mint-tea.
  • Asha's network: the course's own server played Fast 4G, as in Module 33. Each answer waited 165 ms. Building a tea's data took Ravi's server 250 ms more.
  • Asha's computer: Chrome 157, in a window 500 pixels wide, with the CPU 4 times slower.
  • Real taps: mouse clicks, sent the way DevTools sends them. Chrome passes these straight to the page. Back went through the browser's own history, as the Back button does.
  • Timing: Chrome took a screenshot of every frame it drew. Each version was tapped 5 times, taking turns.

Loading a route's code and data together, and early

Ravi split his app the way lesson 22.4 showed. The tea page's code sits in its own file, a chunk. The list never needs it, so the first visit stays small. The chunk is loaded with import() the first time a tea page is shown.

Here is his first openTea. His app runs it when Asha taps a tea:

The code, then the dataJavaScript
async function openTea(slug) {  const { teaPage } = await import("./tea-page.js");  const tea = await getJSON(`data/${slug}.json`);  app.replaceChildren(teaPage(tea));  scrollTo(0, 0);}
  • Line 1 starts openTea. slug is the tea's short name, like mint-tea.
  • Line 2 asks for the chunk with import(). await means: wait here until it has arrived.
  • Line 3 asks for the tea's data with getJSON, a small helper around fetch(). It runs only after line 2 is done.
  • Line 4 draws the tea page in place of the list. Line 5 scrolls to the top.

Look at lines 2 and 3 again. The data can't even be asked for until the code is back. That's a request waterfall: a chain of requests where each one waits for the one before. Lesson 22.4 met them between chunks. Here, the chain is code, then data. The course timed both trips:

Two trips, one after the otherPop out in the code editor (opens in a new tab)JavaScript
// Asha's tap, with the code first and the data after it. In ms after the tap.const code = { start: 3.4, end: 170.1 };const data = { start: 171.7, end: 587.9 }; console.log(`The code took ${(code.end - code.start).toFixed(1)} ms.`);console.log(`The data started at ${data.start} ms and took ${(data.end - data.start).toFixed(1)} ms.`);
  • Line 2 holds when the chunk's request left, and when its last byte arrived. Line 3 does the same for the data.
  • Line 5 prints The code took 166.7 ms.
  • Line 6 prints The data started at 171.7 ms and took 416.2 ms.

Each trip began with the 165 ms wait that every answer had. The data also waited 250 ms for Ravi's server. Their sizes hardly mattered: the chunk was 466 bytes, and the data 179. Then Chrome drew the page, and it was on screen at 613.5 ms. Why it matters: on a slow network, two trips in a row cost two waits, even for tiny files.

Real-life analogyPasta and sauce at the same time

You're making pasta for a friend. You can wait for the water to boil, cook the pasta, and only then start the sauce. Or you can put the water on and make the sauce while it heats. Dinner is ready when the slower one is done. Better still, put the water on when you see your friend coming up the path.

In real life: Boiling the water, then starting the sauce
In JavaScript: The code, then the data
In real life: Both on the stove at once
In JavaScript: Promise.all([import(), getJSON()])
In real life: Dinner is ready when the slower one is done
In JavaScript: The page waits for the longer trip
In real life: Starting when your friend comes up the path
In JavaScript: Starting when the pointer comes onto a tea

Ravi's second version starts both trips at once:

The code and the data togetherJavaScript
async function openTea(slug) {  const [{ teaPage }, tea] = await Promise.all([    import("./tea-page.js"),    getJSON(`data/${slug}.json`),  ]);  app.replaceChildren(teaPage(tea));  scrollTo(0, 0);}
  • Lines 2 to 5 put both requests in Promise.all. It starts them together, and waits until both have arrived.
  • Line 2 unpacks the two results: teaPage from the chunk, and tea from the data.
  • Lines 6 and 7 are the same as before.
How much soonerPop out in the code editor (opens in a new tab)JavaScript
// When was the tea page on screen? In ms after the tap, the middle of 5 taps.const codeThenData = 613.5;const together = 436; console.log(`Together: ${together} ms, ${(codeThenData - together).toFixed(1)} ms sooner.`);

Line 5 prints Together: 436 ms, 177.5 ms sooner. The code was back at 170.9 ms, long before the data at 420.7 ms. So the code's trip was hidden inside the data's. Why it matters: when a view needs two things, the wait is the slower one, not the two added up.

The data's trip is still long, and it starts only at the tap. Can it start before? On a computer, there's a good sign that a tap is coming: the pointer. Lesson 33.3 used it to prefetch whole pages. Ravi uses it inside his app:

Start loading when the pointer arrivesJavaScript
const started = new Map();function load(slug) {  if (!started.has(slug)) started.set(slug, Promise.all([import("./tea-page.js"), getJSON(`data/${slug}.json`)]));  return started.get(slug);}app.addEventListener("pointerover", (event) => {  const link = event.target.closest("a[data-tea]");  if (link) load(link.dataset.tea);});
  • Line 1 makes a Map, a list of keys and values. It keeps each tea's load once it has started.
  • Line 3 starts the code and the data together, unless that tea's load has already started.
  • Line 4 hands back the promise: the same one every time.
  • Lines 6 to 9 listen for pointerover, which fires when the pointer comes onto an element. If it's a tea's link, they call load().
The tap uses what the pointer startedJavaScript
async function openTea(slug) {  const [{ teaPage }, tea] = await load(slug);  app.replaceChildren(teaPage(tea));  scrollTo(0, 0);}

Line 2 is the only change in openTea. It awaits the load the pointer started, instead of starting a new one. So nothing is fetched twice. The course rested the pointer on Mint tea for 300 ms, then tapped:

The head startPop out in the code editor (opens in a new tab)JavaScript
// The pointer rested on Mint tea for 300 ms, then Asha tapped. In ms after the tap.const started = -304.3;const dataArrived = 112.7;const onScreen = 136.5; console.log(`Both left ${-started} ms before the tap.`);console.log(`The data came ${dataArrived} ms after it. The page was on screen at ${onScreen} ms.`);
  • Lines 2 to 4 are the recorded times. A negative time is before the tap.
  • Line 6 prints Both left 304.3 ms before the tap.
  • Line 7 prints The data came 112.7 ms after it. The page was on screen at 136.5 ms.

The data still had a little way to go at the tap. A longer rest would leave less. Here are the three versions on one time scale:

The tea page's two requests in three versions of Ravi's app, to scale, in ms after the tap. Code, then data: the code from 3.4 ms to 170.1 ms, the data from 171.7 ms to 587.9 ms, the tea page on screen at 613.5 ms. Together: the code from 3.4 ms to 170.9 ms, the data from 3.6 ms to 420.7 ms, the tea page on screen at 436 ms. On hover: the code from -304.3 ms to -136.6 ms, the data from -304.3 ms to 112.7 ms, the tea page on screen at 136.5 ms.Code, then dataon screen at 613.5 msTogetheron screen at 436 msOn hoveron screen at 136.5 msthe tap-300 ms600 msthe code, tea-page.jsthe data, mint-tea.json
Each bar is one trip to the server, drawn to scale. The page can't be drawn until both trips are back.

Pick a version to see its numbers:

Playground: four ways to start loading
Ravi's openTeaJavaScript
async function openTea(slug) {
  const { teaPage } = await import("./tea-page.js");
  const tea = await getJSON(`data/${slug}.json`);
  app.replaceChildren(teaPage(tea));
  scrollTo(0, 0);
}
Code, then data, after the tapRecorded
The code, tea-page.js, left3.4 ms after the tap
The code arrived170.1 ms after the tap
The data, mint-tea.json, left171.7 ms after the tap
The data arrived587.9 ms after the tap
The screen first changed613.5 ms after the tap
The tea page was on screen613.5 ms after the tap
Try it yourself
Code, then data, after the tap

The data asked for nothing until the code had arrived. Two trips, one after the other, and the list sat unchanged the whole time.

Recorded in Chrome 157, with a CPU 4 times slower and a server that played Fast 4G. Each version's middle tap of 5. In the bars, the thin line is the tap and the thick one is the tea page on screen.

Routers can do these jobs for you. TanStack Router loads a route's code and runs its loader in parallel. A loader is the function that fetches a route's data. With defaultPreload: 'intent', it starts both when the pointer rests on a link for 50 ms, or at once when a finger touches it. React Router waits for the next page's loaders before it shows the page. Next.js links prefetch by themselves, as lesson 33.3 showed.

Why it matters: the tap is the latest moment to start. Start both trips together, and start them at the first sign.

Showing the new view at once

Back to Ravi's second version, with both trips together. Asha taps Mint tea. For 436 ms, the list doesn't change at all. She can't tell that her tap worked. Did she miss the link? Is the shop broken? Many people tap again.

Real-life analogyA waiter who sets your table at once

You order at a restaurant, and the kitchen needs twenty minutes. A good waiter brings cutlery and a glass of water at once. The food is no faster. But you know your order was heard. With nothing on the table for twenty minutes, you'd wave at the waiter again.

In real life: Cutlery and water, brought at once
In JavaScript: The tea page's empty frame, drawn in the click
In real life: The food
In JavaScript: The tea's code and data
In real life: Waving at the waiter again
In JavaScript: A second tap

Ravi's third version draws the tea page's shape first. A skeleton, or frame, is a set of grey shapes where the content will go. His lives in the main script, app.js, not in the chunk. It has to be ready before anything is loaded:

The tea page's frameJavaScript
function teaFrame() {  const frame = document.createElement("article");  frame.className = "tea-page frame";  frame.innerHTML = '<div class="hero-box"></div><p class="bar wide"></p><p class="bar"></p>';  return frame;}
  • Line 2 makes an article element, the same kind the tea page uses.
  • Line 4 fills it with a grey box where the photo goes, and two grey bars for the name and the price.
  • Line 5 hands it back. There's no tea in it yet.
The frame first, in the same clickJavaScript
async function openTea(slug) {  app.replaceChildren(teaFrame());  scrollTo(0, 0);  const [{ teaPage }, tea] = await Promise.all([    import("./tea-page.js"),    getJSON(`data/${slug}.json`),  ]);  app.replaceChildren(teaPage(tea));}

Lines 2 and 3 run before the first await. So the frame is drawn in the same click, before any request has left. Lines 4 to 8 are the parallel load from before. Here are both versions, frame by frame:

Two versions of Ravi's app, in real frames from Chrome. Nothing drawn at once: the list stays until the tea page appears at 436 ms. The frame at once: the tea page's grey frame appears at 20.2 ms, and the tea page at 436.9 ms.Nothing drawn at onceRavi's list at the tap, with Mint tea at the top.the tap20.2 ms after the tap: the same list. Nothing has changed.20.2 ms: no change436 ms after the tap: the Mint tea page.436 msThe frame at onceRavi's list at the tap, with Mint tea at the top.the tap20.2 ms after the tap: the tea page's empty frame, a grey box where the photo goes and two grey bars.20.2 ms436.9 ms after the tap: the Mint tea page.436.9 msno sign of the tapthe tap shows at once
Real frames, the middle of 5 taps each. The tea arrived at the same time in both. Only the frame showed Asha at once that her tap had worked.

The frame was on screen 20.2 ms after the tap. The tea page came at 436.9 ms, as before. The data was no faster. But Asha saw at once that her tap had worked. Why it matters: a frame drawn in the click turns a dead pause into a page that's on its way.

There's a second reason, and it's about INP. Lesson 26.1 showed how INP times a tap: from the tap to the next paint after the tap's code has run. Here is what Event Timing, the API behind INP, recorded for each tap:

Each click's next paintPop out in the code editor (opens in a new tab)JavaScript
// Each click's next paint, from Event Timing, in 5 taps each.// null means under 16 ms: too short for the observer to report.const nothingAtOnce = [432, null, null, 432, null];const frameAtOnce = [16, null, 16, null, null];const slow = (taps) => taps.filter((ms) => ms > 200).length; console.log(`Nothing at once: ${slow(nothingAtOnce)} of 5 taps over 200 ms`);console.log(`Frame at once: ${slow(frameAtOnce)} of 5 taps over 200 ms`);
  • Lines 3 and 4 hold each tap's next paint, in ms. null means under 16 ms. The course's observer only reports events of 16 ms or more.
  • Line 5 counts the taps over 200 ms, the limit for a good INP.
  • It prints Nothing at once: 2 of 5 taps over 200 ms and Frame at once: 0 of 5 taps over 200 ms.

Ravi's click code ran for only a few milliseconds. So why 432 ms? When nothing on the screen changes, a browser may skip drawing a frame. The HTML Standard calls this unnecessary rendering. With no new frame, the next paint after the tap was the tea page itself. In the other three taps, Chrome reported a paint within 16 ms. Still, nothing on screen changed until the tea page. With the frame, there was always something new to paint. Why it matters: an empty pause can count against INP, not just against Asha's patience.

Frameworks give you a place for the frame. In Next.js, a loading.js file is an "instant loading state". It is shown at once and prefetched with the link. In React Router, useNavigation() tells you a navigation is pending, so you can show it. TanStack Router shows a route's pending component only after 1 second by default, and then for at least 500 ms, so it never flashes. For a route like Ravi's, ready in under half a second, that means nothing is drawn in between. Lesson 2.2 compared skeletons and spinners.

Try it in your own browser. This one is a demo: a timer stands in for the code and the data.

Playground: your own tap
What the lab doesJavaScript
// What the lab does when you tap, shortened.button.addEventListener("click", () => {  if (frameAtOnce) showFrame();  setTimeout(showTea, 436); // a timer stands in for the code and the data});new PerformanceObserver(readClick).observe({ type: "event", durationThreshold: 16 });
Ravi's app, a demothe list
  • Mint tea, £4.50
  • Green tea, £5.00
  • Chamomile, £3.80
Your click's next paintTap Mint tea to measure.
Try it yourself
Nothing drawn at once

Tap Mint tea. A timer stands in for the code and the data, set to the time Ravi's app took. This is a demo, not a real route change.

A demo in your own browser: the wait is a 436 ms timer. The next paint is your click's duration from Event Timing, the measure INP uses. It changes from tap to tap.

Lines 3 and 4 of the lab's code show the frame first, then wait. Tap with the box ticked and unticked. Watch whether the screen changes at once.

Back to the same place: scroll restoration

Asha scrolls down Ravi's list, past six teas, to Rooibos. That's 2,398 pixels from the top. She opens Rooibos, reads it, and presses Back. She expects the list where she left it, with Rooibos on screen.

In a multi-page site, the back/forward cache from lesson 33.1 might keep the whole page. Here, it can't help. Back never leaves the page: the app just swaps the view again. So the app has to bring the list back. And something has to put it back at 2,398 pixels. Putting the old scroll position back is called scroll restoration.

Real-life analogyA bookmark needs its book

You hand a library book back with a bookmark at page 240. Later you ask for it again. The librarian has your bookmark ready. But the book is still on the returns trolley. All she has on the desk is a thin leaflet, with no page 240. A good librarian waits until the book is on the desk, then opens it at the bookmark.

In real life: The bookmark
In JavaScript: The saved scroll position, 2,398 px
In real life: The book
In JavaScript: The list
In real life: The thin leaflet on the desk
In JavaScript: Rooibos's page, still on screen
In real life: Waiting until the book is on the desk
In JavaScript: Scrolling only after the list is drawn

Ravi first left scrolling to the browser. That's the default: history.scrollRestoration is "auto". Each address Asha visits in the tab gets a history entry, and Back steps through them. The browser keeps the list's scroll position in its entry. Chrome saves it there every time the page scrolls. His app fetched the list's data again on Back. Here is where the list came back:

Where the list came backPop out in the code editor (opens in a new tab)JavaScript
// Asha left the list 2398 px down. Where was it after Back?const saved = 2398;const afterBack = 0; console.log(afterBack === saved ? "Back at Rooibos" : `Lost: ${saved - afterBack} px from where she was`);
  • Line 2 is where Asha left the list. Line 3 is where it came back, in all three tries.
  • Line 5 prints Lost: 2398 px from where she was.

The list came back at the top, with Mint tea in the middle of the screen. Why? The HTML Standard sets the order. On Back inside the same page, the browser first fires popstate, the event that tells the page its address changed. Right after that, it restores the scroll position. Chrome's code does the same, in document_loader.cc: popstate first, then the scroll. Chrome stores the position and asks for a new frame to apply it in.

Ravi's popstate handler only started fetching the list. The list arrived about 170 ms later. When Chrome put the scroll back, Rooibos's page was still on screen. It fits on the screen, so it couldn't scroll at all. Then the list arrived, at the top. The bookmark came before the book.

The browser's way works when the list is drawn inside popstate. Ravi tried keeping the list's data in memory after the first visit:

The list, kept in memoryJavaScript
let teas = null;async function showList() {  teas ??= await getJSON("data/teas.json");  app.replaceChildren(listView(teas));}

Line 3 fetches only when teas is still null. The ??= operator assigns only when the variable is null or undefined. On Back, nothing is awaited, so line 4 draws the list at once, inside popstate. Chrome's scroll then had the list to work with. Rooibos was on screen 19 ms after Back. Why it matters: the browser's scroll restoration needs the page to be there when popstate ends.

Data often can't stay in memory. So the other choice is to scroll yourself. Ravi's next version does that:

Ravi puts the scroll back himselfJavaScript
history.scrollRestoration = "manual";function route(url = new URL(location.href)) {  const slug = url.searchParams.get("tea");  return slug ? openTea(slug) : showList();}document.addEventListener("click", (event) => {  const link = event.target.closest("a[data-route]");  if (!link) return;  event.preventDefault();  history.replaceState({ scrollY }, "");  history.pushState(null, "", link.href);  route();});addEventListener("popstate", async (event) => {  await route();  scrollTo(0, event.state?.scrollY ?? 0);});route();
  • Line 1 sets scrollRestoration to "manual", so the browser won't try. The HTML Standard suggests setting it as early as you can, so every entry gets it.
  • Lines 6 to 13 handle a tap on a link. Line 10 saves scrollY, how far the page is scrolled. replaceState stores it in the list's own history entry, without adding a new one. Then line 11 adds the tea's entry.
  • Lines 14 to 17 handle Back. Line 15 waits until the list is drawn. Line 16 scrolls to the saved place.

The list came back at Rooibos in its first frame, 185.6 ms after Back. Then Ravi tried one small change: he scrolled a frame later, after the list was first drawn. That first frame showed the top of the list, at 188.4 ms. The next, at 205 ms, jumped to Rooibos. Why it matters: draw and scroll in the same task, or the list jumps in front of Asha.

Newer browsers offer a cleaner way: the Navigation API. Instead of a click listener and a popstate listener, one listener sees every navigation in the page:

One listener for every link and every BackJavaScript
function route(url) {  const slug = url.searchParams.get("tea");  return slug ? openTea(slug) : showList();}navigation.addEventListener("navigate", (event) => {  if (!event.canIntercept || event.hashChange || event.downloadRequest) return;  const url = new URL(event.destination.url);  event.intercept({ handler: () => route(url) });});route(new URL(location.href));
  • Line 5 listens for navigate. It fires for a tapped link, a submitted form, and Back and Forward.
  • Line 6 skips what the page shouldn't take over. canIntercept is false for a link to another site, for example. The other two are a change of #fragment only, and a download.
  • Line 8 calls intercept(). The browser stays on the page and runs the handler, Ravi's route(), instead of loading a new page.

Here is the part that matters for scrolling. By default, the browser waits for the handler's promise to settle. Then it scrolls: back to the saved place for Back, or to the top for a new page. So the list is always drawn first. In Chrome's code, an intercepted navigation skips the usual scroll (document_loader.cc). It scrolls once the handler is done (navigate_event.cc). The browser also moves focus back to the page's body, or to an element marked autofocus. The option focusReset: "manual" turns that off.

Ravi's list came back at Rooibos in its first frame, 204 ms after Back, with no jump. Here are the three Backs that differed most:

Asha presses Back after opening Rooibos from far down the list, in three versions of Ravi's app, in real frames from Chrome. The browser restores, before the list is back: before Back, Before Back: the Rooibos page, with its photo, name, price and a link back to the teas. Then 186.3 ms, 186.3 ms after Back: the list, at the top, with Mint tea. Ravi restores, a frame after the list: before Back, Before Back: the Rooibos page, with its photo, name, price and a link back to the teas. Then 188.4 ms, 188.4 ms after Back: the list, at the top, with Mint tea. Then 205 ms, 205 ms after Back: the list, scrolled down to Rooibos. The Navigation API restores, after the handler: before Back, Before Back: the Rooibos page, with its photo, name, price and a link back to the teas. Then 204 ms, 204 ms after Back: the list, scrolled down to Rooibos.The browser restores, before the list is backBefore Back: the Rooibos page, with its photo, name, price and a link back to the teas.before Back186.3 ms after Back: the list, at the top, with Mint tea.186.3 msback at the topRavi restores, a frame after the listBefore Back: the Rooibos page, with its photo, name, price and a link back to the teas.before Back188.4 ms after Back: the list, at the top, with Mint tea.188.4 ms205 ms after Back: the list, scrolled down to Rooibos.205 msthe top, then a jumpThe Navigation API restores, after the handlerBefore Back: the Rooibos page, with its photo, name, price and a link back to the teas.before Back204 ms after Back: the list, scrolled down to Rooibos.204 msback at Rooibos
Real frames from Chrome, all times in ms after Back. Only the Navigation API brought the list back at Rooibos in its first frame.

Read the table across: each row is one way Ravi brought the list back.

Five ways to bring the list back on Back
How the list came backWho scrolled, and whenWhere the list endedDid a frame show the wrong place?
auto, the list fetched againChrome, right after popstate, while Rooibos's page was still on screen.At the top, with Mint tea in the middle.No. It never reached Rooibos.
auto, the list kept in memoryChrome, right after popstate. The list was already drawn by then.At Rooibos, 19 ms after Back.No.
manual, Ravi scrolls once the list is drawnRavi's code, in the same task that drew the list.At Rooibos, 185.6 ms after Back.No.
manual, Ravi scrolls a frame laterRavi's code, after the list's first frame.At Rooibos, 205 ms after Back.Yes. At 188.4 ms it showed the top.
The Navigation APIChrome, once the handler's promise settled.At Rooibos, 204 ms after Back.No.

Try each way, and look at each frame of the list:

Playground: five ways back
The part of Ravi's code that changesJavaScript
// No scroll code. On Back, the list is fetched again.
addEventListener("popstate", () => route());
After BackRecorded
Asha left the list at2,398 px down
The list was drawn again171.4 ms after Back
Frame 1 of the list, at 186.3 msthe top of the list
In the middle of the screen at the endMint tea
A frame showed the wrong place firstno
Try it yourself
The browser restores; the list is fetched again

Chrome put the scroll back right after popstate. The list wasn't there yet, and Rooibos's page couldn't scroll. The list then came in at the top.

Recorded in Chrome 157: Asha scrolled down to Rooibos, opened it, and pressed the browser's Back. Times are in ms after Back, from Chrome's screenshots. The middle of 3 tries.

Routers have their own versions of this. React Router's ScrollRestoration component copies the browser's way, and keeps the positions in sessionStorage. TanStack Router, with scrollRestoration: true, restores "after successful navigations before DOM paint". Why it matters: whoever scrolls, the list must be drawn first, and the scroll must come before that frame is painted.

Long sessions: what each route change leaves behind

In a multi-page site, every new page starts with clean memory. The old page is thrown away, or kept whole in the back/forward cache. A single-page app never gets that fresh start. The same page lives for the whole visit, so whatever each route change leaves behind stays. Ben's shop in lesson 29.2 kept every tea page he opened. Ravi's app has a leak of its own.

Real-life analogyA hotel room that's never cleaned between guests

In a hotel, each guest gets a freshly cleaned room. Now picture one room that hosts guest after guest, and nobody cleans in between. Each guest leaves a towel on the floor. After twenty guests, the room is full of towels.

In real life: A freshly cleaned room
In JavaScript: A new page in a multi-page site
In real life: One room for every guest
In JavaScript: One page for the whole visit
In real life: A towel left on the floor
In JavaScript: A listener a tea page never removes
In real life: Cleaning between guests
In JavaScript: leave(), run on each route change

Ravi's tea page shows a small bar with the tea's price once Asha scrolls down. These two lines in tea-page.js do it:

A scroll listener on the windowJavaScript
const bar = page.querySelector(".buy-bar");addEventListener("scroll", () => { bar.hidden = scrollY < 200; }, { signal });
  • Line 1 finds the bar in the tea page.
  • Line 2 adds a scroll listener to the window. Its function uses bar, so it keeps the bar, and the whole tea page around it, in memory.
  • The signal option would let Ravi remove it later. But his openTea never passed one, so nothing ever removes it.

The window lasts as long as the page. So each tea page Asha leaves stays in memory, held by its listener. The course made 20 round trips: a tea page, then back to the list, each time. That's 40 route changes. Back on the list, it cleaned up memory and counted, as lesson 29.2 did. It counted DOM nodes, the pieces of the page, like an element or a run of text. It also counted listeners:

What each round trip left behindPop out in the code editor (opens in a new tab)JavaScript
// DOM nodes and listeners after 0 and 20 round trips, each count after a clean-up.const leaky = { nodes: [88, 488], listeners: [3, 23] };const fixed = { nodes: [88, 88], listeners: [3, 3] };const perTrip = ([first, last]) => (last - first) / 20; console.log(`Leaky: ${perTrip(leaky.nodes)} nodes and ${perTrip(leaky.listeners)} listener per round trip`);console.log(`Fixed: ${perTrip(fixed.nodes)} nodes and ${perTrip(fixed.listeners)} listeners per round trip`);
  • Lines 2 and 3 hold the counts after 0 and 20 round trips.
  • Line 4 works out what each trip added.
  • It prints Leaky: 20 nodes and 1 listener per round trip and Fixed: 0 nodes and 0 listeners per round trip.

20 nodes is exactly one of Ravi's tea pages. One per trip, never freed. The JS heap, the memory that holds the page's JavaScript objects, didn't show it. Both versions' heaps grew by 50 to 60 kB in the first five trips, as the app warmed up. After that, each moved by less than 2 kB. The tea pages are DOM nodes, and Chrome counts those separately. Why it matters: count DOM nodes and listeners, not only the heap. A real tea page, with reviews, holds far more nodes than Ravi's.

Here is the fix:

Clean up when the tea page leavesJavaScript
let leave = null;async function openTea(slug) {  const stop = new AbortController();  leave = () => {    stop.abort();    started.delete(slug);  };  app.replaceChildren(teaFrame());  scrollTo(0, 0);  const [{ teaPage }, tea] = await load(slug);  app.replaceChildren(teaPage(tea, stop.signal));}
  • Line 3 makes an AbortController for this visit. Its signal can cancel many things at once.
  • Lines 4 to 7 keep a leave() function. It aborts the controller, which removes every listener added with its signal. It also forgets this tea's load in the started Map.
  • Line 11 passes the signal to the tea page, so its scroll listener uses it.
The router lets the old view clean up firstJavaScript
function route(url = new URL(location.href)) {  leave?.();  leave = null;  const slug = url.searchParams.get("tea");  return slug ? openTea(slug) : showList();}

Lines 2 and 3 run first on every route change. The view before cleans up, and is forgotten. The fixed app stayed at 88 DOM nodes and 3 listeners for all 20 trips.

Why forget the started load too? A cache that never forgets grows with every route a visitor opens. Ravi's Map could hold at most his 8 teas. A shop with 800 teas could hold 800 by the end of a long visit. A cache needs a limit, like leftovers in a fridge. TanStack Router keeps unused loader data for 5 minutes by default. After that, it may prune it.

Pick a number of round trips:

Playground: a long session
20 round tripsNothing cleaned up · Cleaned up on leave
DOM nodes
48888
JS event listeners
233
JS heap, kB
577.3581.8
Try it yourself
After 20 round trips: 488 DOM nodes on the leaky app, 88 on the fixed one

Each count was read back on the list, right after a garbage collection. A round trip is a tea page and back to the list: two route changes.

Recorded in Chrome 157, one long session per version, with Memory.getDOMCounters and Performance.getMetrics. 1 kB is 1,000 bytes.

Lesson 29.2 shows how to find what holds a page, with two heap snapshots. Lesson 29.1 showed why growth matters: on a phone with little memory, a big tab is more likely to be thrown away.

Which fix for which slow route change?

Each problem below comes from a single-page app. Sort it by the fix it needs:

Which fix for which slow route change?
  • A product page asks for its data only after its code has arrived
  • The pointer rests on a link for 300 ms before each click, and nothing loads until the click
  • After a tap on a menu link, the old page stays as it was for 400 ms
  • Visitors tap a link twice, because nothing seems to happen
  • After Back, the list shows its first item, not the one the visitor was reading
  • On Back, the list appears at the top for one frame, then jumps down
  • DOM nodes climb by the same amount every time the visitor opens a product and comes back
  • Each product page adds a resize listener to window and never removes it
Try it yourself
0 of 8 correct

Sort each problem by the fix it needs.

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

Common mix-ups

  • "No new page means no wait." No. The view's code and data still travel. Ravi's tea page took 613.5 ms.
  • "A skeleton makes the page load faster." No. The tea came at about the same time. The frame shows, at once, that the tap worked.
  • "A quick INP means the tap showed something." No. Three of the five taps without a frame had a next paint under 16 ms. Yet nothing on screen changed for over 400 ms.
  • "Leaving scrollRestoration as auto always works." No. The browser restores right after popstate. If the list isn't drawn by then, it lands in the wrong place.
  • "Manual scroll restoration can run whenever it likes." No. One frame late, and the list jumps.
  • "If the JS heap stays level, nothing leaks." No. Ravi's leaky app kept 20 DOM nodes on every trip, with a level heap.

Practice exercises

Answer first, then use the hints.

Exercise 1 · Warm-upA slower server

Ravi's server now takes 250 ms longer to build a tea's data. The code and the data start together. What does this print?

Starter codePop out in the code editor (opens in a new tab)JavaScript
// Ravi's server now takes 250 ms longer to build a tea's data.
const codeArrives = 170.9;
const dataArrives = 420.7 + 250;

console.log(`Both have arrived at ${Math.max(codeArrives, dataArrives).toFixed(1)} ms`);

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

    Exercise 2 · Warm-upA much longer visit

    Asha keeps going on the leaky app, at the same rate, to 100 round trips. What does this print?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const nodesAtStart = 88;
    const nodesPerTrip = 20;
    const trips = 100;
    
    console.log(`${nodesAtStart + nodesPerTrip * trips} DOM nodes`);

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

      Exercise 3 · PracticeDrawn from memory

      In the playground with five ways back, pick the one where the browser restores and the list comes from memory. How many ms after Back was the list drawn again?

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

        Exercise 4 · PracticeThe reviews route

        Ravi's reviews route loads its code, then its data. Rewrite it so both start at once. What do you use?

        Starter codeJavaScript
        async function openReviews(slug) {
          const { reviewsPage } = await import("./reviews-page.js");
          const reviews = await getJSON(`data/${slug}-reviews.json`);
          app.replaceChildren(reviewsPage(reviews));
        }

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

          Exercise 5 · ChallengeRavi's app in DevTools

          Open this copy of Ravi's app in Chrome. It's his first version. Open DevTools and its Performance monitor. Then open Mint tea and tap "Back to the teas", three times. By how much does JS event listeners grow?

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

            Exercise 6 · ChallengeScroll before the rest arrives

            Ravi's list now comes in two parts, and Rooibos is in the first. He wants the browser to put the scroll back as soon as the first part is drawn. Which method of the navigate event does he call where the comment is?

            Starter codeJavaScript
            event.intercept({
              async handler() {
                const firstTeas = await getJSON("data/teas-1.json");
                app.replaceChildren(listView(firstTeas));
                // Put the scroll back here, before the rest arrives.
                const moreTeas = await getJSON("data/teas-2.json");
                addTeas(moreTeas);
              },
            });

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

              Check your understanding

              For each question, ask which job it's about: loading, drawing at once, scrolling back, or cleaning up.

              The fast route changes quiz · 7 questionsScore: first tries count
              1. Question 1 of 7What does the third line of the opening example print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                // Asha taps Mint tea. When was its page on screen, in ms after the tap?
                // The middle of 5 taps each, from Chrome's own screenshots.
                const codeThenData = 613.5;
                const startedOnHover = 136.5;
                
                console.log(`Code, then data: ${codeThenData} ms`);
                console.log(`Started on hover: ${startedOnHover} ms`);
                console.log(`Saved: ${(codeThenData - startedOnHover).toFixed(1)} ms`);

                Choose an answer to see the explanation.

              2. Question 2 of 7The tea page's code takes about 167 ms to arrive, and its data about 417 ms. Started together, when can the page be drawn?

                Choose an answer to see the explanation.

              3. Question 3 of 7With nothing drawn at once, why did Event Timing give two of five taps a next paint of 432 ms?

                Choose an answer to see the explanation.

              4. Question 4 of 7Ravi leaves history.scrollRestoration as auto and fetches the list again on Back. Where did the list come back?

                Choose an answer to see the explanation.

              5. Question 5 of 7With the Navigation API, when does the browser put the scroll back after a Back, by default?

                Choose an answer to see the explanation.

              6. Question 6 of 7After 5 round trips, the leaky app's JS heap stayed level. Was it still leaking?

                Choose an answer to see the explanation.

              7. Question 7 of 7Does Back inside a single-page app use the back/forward cache?

                Choose an answer to see the explanation.

              Key takeaways

              • A route change is a small page load inside one page. The view's code and data still travel.
              • Start the code and the data together, with Promise.all. The wait becomes the longer trip.
              • Start them at the first sign, like the pointer coming onto a link. Ravi's tea page went from 613.5 ms to 136.5 ms.
              • Draw the view's frame in the same click. It shows the tap landed, and gives INP something to paint.
              • Put the scroll back only after the list is drawn: in the same task, or with the Navigation API. Its scroll() method can do it before the handler ends.
              • Clean up each view as it leaves, with an AbortController, and give caches a limit. Count DOM nodes and listeners, not only the heap.

              Remember the one-liner.
              Start early, draw at once, scroll after drawing, and clean up on leave.

              Sources

              The facts on this page come from these specs, docs and source files:

              Coming next: Measuring soft navigations. Core Web Vitals see one page per visit, so Ravi's route changes are invisible to them. Lesson 30.4 already used soft navigations to split CLS by page. Next, you'll measure each route change.

              CompleteFrontend Clear concepts. Working examples.