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.
- 01Load a route earlyStart a route's code and its data together, and before the tap when you can, so neither waits for the other.
- 02Answer every tap at onceDraw the new view's frame in the same click, so the next paint shows that the tap worked.
- 03Keep 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:
Here are the two taps as code:
1// Asha taps Mint tea. When was its page on screen, in ms after the tap?2// The middle of 5 taps each, from Chrome's own screenshots.3const codeThenData = 613.5;4const startedOnHover = 136.5;5 6console.log(`Code, then data: ${codeThenData} ms`);7console.log(`Started on hover: ${startedOnHover} ms`);8console.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 msandSaved: 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.
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
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:
1async function openTea(slug) {2 const { teaPage } = await import("./tea-page.js");3 const tea = await getJSON(`data/${slug}.json`);4 app.replaceChildren(teaPage(tea));5 scrollTo(0, 0);6}- Line 1 starts
openTea.slugis the tea's short name, likemint-tea. - Line 2 asks for the chunk with
import().awaitmeans: wait here until it has arrived. - Line 3 asks for the tea's data with
getJSON, a small helper aroundfetch(). 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:
1// Asha's tap, with the code first and the data after it. In ms after the tap.2const code = { start: 3.4, end: 170.1 };3const data = { start: 171.7, end: 587.9 };4 5console.log(`The code took ${(code.end - code.start).toFixed(1)} ms.`);6console.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.
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:
1async function openTea(slug) {2 const [{ teaPage }, tea] = await Promise.all([3 import("./tea-page.js"),4 getJSON(`data/${slug}.json`),5 ]);6 app.replaceChildren(teaPage(tea));7 scrollTo(0, 0);8}- 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:
teaPagefrom the chunk, andteafrom the data. - Lines 6 and 7 are the same as before.
1// When was the tea page on screen? In ms after the tap, the middle of 5 taps.2const codeThenData = 613.5;3const together = 436;4 5console.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:
1const started = new Map();2function load(slug) {3 if (!started.has(slug)) started.set(slug, Promise.all([import("./tea-page.js"), getJSON(`data/${slug}.json`)]));4 return started.get(slug);5}6app.addEventListener("pointerover", (event) => {7 const link = event.target.closest("a[data-tea]");8 if (link) load(link.dataset.tea);9});- 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 callload().
1async function openTea(slug) {2 const [{ teaPage }, tea] = await load(slug);3 app.replaceChildren(teaPage(tea));4 scrollTo(0, 0);5}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:
1// The pointer rested on Mint tea for 300 ms, then Asha tapped. In ms after the tap.2const started = -304.3;3const dataArrived = 112.7;4const onScreen = 136.5;5 6console.log(`Both left ${-started} ms before the tap.`);7console.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:
Pick a version to see its numbers:
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);
}3.4 ms after the tap170.1 ms after the tap171.7 ms after the tap587.9 ms after the tap613.5 ms after the tap613.5 ms after the tapThe data asked for nothing until the code had arrived. Two trips, one after the other, and the list sat unchanged the whole time.
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.
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:
1function teaFrame() {2 const frame = document.createElement("article");3 frame.className = "tea-page frame";4 frame.innerHTML = '<div class="hero-box"></div><p class="bar wide"></p><p class="bar"></p>';5 return frame;6}- 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.
1async function openTea(slug) {2 app.replaceChildren(teaFrame());3 scrollTo(0, 0);4 const [{ teaPage }, tea] = await Promise.all([5 import("./tea-page.js"),6 getJSON(`data/${slug}.json`),7 ]);8 app.replaceChildren(teaPage(tea));9}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:
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:
1// Each click's next paint, from Event Timing, in 5 taps each.2// null means under 16 ms: too short for the observer to report.3const nothingAtOnce = [432, null, null, 432, null];4const frameAtOnce = [16, null, 16, null, null];5const slow = (taps) => taps.filter((ms) => ms > 200).length;6 7console.log(`Nothing at once: ${slow(nothingAtOnce)} of 5 taps over 200 ms`);8console.log(`Frame at once: ${slow(frameAtOnce)} of 5 taps over 200 ms`);- Lines 3 and 4 hold each tap's next paint, in ms.
nullmeans 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 msandFrame 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.
1// What the lab does when you tap, shortened.2button.addEventListener("click", () => {3 if (frameAtOnce) showFrame();4 setTimeout(showTea, 436); // a timer stands in for the code and the data5});6new PerformanceObserver(readClick).observe({ type: "event", durationThreshold: 16 });- Mint tea, £4.50
- Green tea, £5.00
- Chamomile, £3.80
Tap Mint tea to measure.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.
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.
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:
1// Asha left the list 2398 px down. Where was it after Back?2const saved = 2398;3const afterBack = 0;4 5console.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:
1let teas = null;2async function showList() {3 teas ??= await getJSON("data/teas.json");4 app.replaceChildren(listView(teas));5}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:
1history.scrollRestoration = "manual";2function route(url = new URL(location.href)) {3 const slug = url.searchParams.get("tea");4 return slug ? openTea(slug) : showList();5}6document.addEventListener("click", (event) => {7 const link = event.target.closest("a[data-route]");8 if (!link) return;9 event.preventDefault();10 history.replaceState({ scrollY }, "");11 history.pushState(null, "", link.href);12 route();13});14addEventListener("popstate", async (event) => {15 await route();16 scrollTo(0, event.state?.scrollY ?? 0);17});18route();- Line 1 sets
scrollRestorationto"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.replaceStatestores 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:
1function route(url) {2 const slug = url.searchParams.get("tea");3 return slug ? openTea(slug) : showList();4}5navigation.addEventListener("navigate", (event) => {6 if (!event.canIntercept || event.hashChange || event.downloadRequest) return;7 const url = new URL(event.destination.url);8 event.intercept({ handler: () => route(url) });9});10route(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.
canInterceptis 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'sroute(), 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:
Read the table across: each row is one way Ravi brought the list back.
| How the list came back | Who scrolled, and when | Where the list ended | Did a frame show the wrong place? |
|---|---|---|---|
auto, the list fetched again | Chrome, 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 memory | Chrome, right after popstate. The list was already drawn by then. | At Rooibos, 19 ms after Back. | No. |
manual, Ravi scrolls once the list is drawn | Ravi's code, in the same task that drew the list. | At Rooibos, 185.6 ms after Back. | No. |
manual, Ravi scrolls a frame later | Ravi'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 API | Chrome, once the handler's promise settled. | At Rooibos, 204 ms after Back. | No. |
Try each way, and look at each frame of the list:
// No scroll code. On Back, the list is fetched again.
addEventListener("popstate", () => route());2,398 px down171.4 ms after Backthe top of the listMint teanoChrome 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.
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.
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:
1const bar = page.querySelector(".buy-bar");2addEventListener("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
signaloption would let Ravi remove it later. But hisopenTeanever 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:
1// DOM nodes and listeners after 0 and 20 round trips, each count after a clean-up.2const leaky = { nodes: [88, 488], listeners: [3, 23] };3const fixed = { nodes: [88, 88], listeners: [3, 3] };4const perTrip = ([first, last]) => (last - first) / 20;5 6console.log(`Leaky: ${perTrip(leaky.nodes)} nodes and ${perTrip(leaky.listeners)} listener per round trip`);7console.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 tripandFixed: 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:
1let leave = null;2async function openTea(slug) {3 const stop = new AbortController();4 leave = () => {5 stop.abort();6 started.delete(slug);7 };8 app.replaceChildren(teaFrame());9 scrollTo(0, 0);10 const [{ teaPage }, tea] = await load(slug);11 app.replaceChildren(teaPage(tea, stop.signal));12}- Line 3 makes an
AbortControllerfor this visit. Itssignalcan 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 thestartedMap. - Line 11 passes the signal to the tea page, so its scroll listener uses it.
1function route(url = new URL(location.href)) {2 leave?.();3 leave = null;4 const slug = url.searchParams.get("tea");5 return slug ? openTea(slug) : showList();6}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:
- DOM nodes
48888- JS event listeners
233- JS heap, kB
577.3581.8
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.
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:
- 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
Sort each problem by the fix it needs.
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.
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?
// 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`);Both have arrived at 670.7 ms. The code still arrives early. Only the data's trip got longer, so the whole wait grows by the same 250 ms.
Asha keeps going on the leaky app, at the same rate, to 100 round trips. What does this print?
const nodesAtStart = 88;
const nodesPerTrip = 20;
const trips = 100;
console.log(`${nodesAtStart + nodesPerTrip * trips} DOM nodes`);2088 DOM nodes. A leak grows with the length of the visit. On the fixed app, it would still be 88.
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?
2.4 ms after Back. Nothing was awaited, so the list was drawn inside popstate. That's why Chrome's scroll, which comes right after popstate, found it there.
Ravi's reviews route loads its code, then its data. Rewrite it so both start at once. What do you use?
async function openReviews(slug) {
const { reviewsPage } = await import("./reviews-page.js");
const reviews = await getJSON(`data/${slug}-reviews.json`);
app.replaceChildren(reviewsPage(reviews));
}async function openReviews(slug) {
const [{ reviewsPage }, reviews] = await Promise.all([
import("./reviews-page.js"),
getJSON(`data/${slug}-reviews.json`),
]);
app.replaceChildren(reviewsPage(reviews));
}Promise.all starts the import() and the getJSON() at the same moment, and waits until both have arrived. The wait becomes the longer trip, not the two added up.
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?
By 3. This copy is Ravi's first version, with the leak: each tea page adds a scroll listener to the window, and nothing removes it. The count never goes back down.
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?
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);
},
});event.intercept({
async handler() {
const firstTeas = await getJSON("data/teas-1.json");
app.replaceChildren(listView(firstTeas));
event.scroll();
const moreTeas = await getJSON("data/teas-2.json");
addTeas(moreTeas);
},
});event.scroll() runs the browser's usual scroll restoration right away, instead of after the handler. Rooibos is in the first part, so the list can go back there before the rest arrives.
Check your understanding
For each question, ask which job it's about: loading, drawing at once, scrolling back, or cleaning up.
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.
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.
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.
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.
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.
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.
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:
- import(): dynamic imports, MDN.
- TanStack Router: Data loading, TanStack.
- TanStack Router: Preloading, TanStack.
- React Router: Pending UI, React Router.
- HTML Standard: update the rendering (unnecessary rendering), WHATWG.
- Next.js: loading.js, Vercel.
- HTML Standard: updating the document for a history step (popstate, then restore persisted state), WHATWG.
- HTML Standard: history.scrollRestoration, WHATWG.
- History API: scroll restoration, Chrome for Developers.
- paint_layer_scrollable_area.cc, lines 526 to 529: every scroll is saved in the history entry, Chromium source.
- document_loader.cc, lines 1927 to 1976: popstate first, then the scroll, Chromium source.
- frame_loader.cc, lines 1567 to 1590: the position waits for the next frame, Chromium source.
- HTML Standard: the Navigation API, WHATWG.
- Modern client-side routing: the Navigation API, Chrome for Developers.
- document_loader.cc, lines 1824 to 1830: an intercepted navigation skips the usual scroll, Chromium source.
- navigate_event.cc, lines 526 to 531: the scroll waits for the handler's promise, Chromium source.
- navigate_event.cc, lines 689 to 715: the scroll itself, Chromium source.
- React Router: ScrollRestoration, React Router.
- TanStack Router: Scroll restoration, TanStack.
- NavigateEvent: scroll() method, MDN.
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.