9. Loading a Page — The Critical Rendering Path
“The fastest request is the one the browser started before you asked.”
The story: the newspaper printing press
Section titled “The story: the newspaper printing press”It’s 1 a.m. at a newspaper’s printing plant. Pages arrive from the newsroom one at a time. A typesetter reads each page top to bottom and sets it in metal. The presses can’t roll until the whole front page is set and the ink colours for this edition have arrived — print the front page in the wrong colours and you’d have to reprint every copy.
The typesetter has a problem. Every so often, a page contains a note saying “STOP — the editor may rewrite everything below this line.” When that happens, the typesetter must stop and wait for the editor, who is slow and might be on the phone.
So the plant hires a runner. While the typesetter waits, the runner skims ahead through the remaining pages — not reading them properly, just looking for anything that needs fetching: photos from the archive, ink from the store room, an advertisement from another building — and sends for them immediately. By the time the editor finishes and the typesetter resumes, half the materials are already on the table.
The typesetter is the HTML parser. The ink is CSS, which blocks rendering. The “STOP” notes are classic <script> tags, which block parsing. And the runner is the preload scanner, one of the most important and least-known pieces of performance engineering in the browser.
The navigation lifecycle
Section titled “The navigation lifecycle”From Priya’s tap to a fully loaded page, a navigation passes through these moments:
beforeunloadon the old page — the chance to say “you have unsaved changes.” (Registering this handler can make the page ineligible for bfcache in some browsers; use it only when there really are unsaved changes.)- Network: the browser process makes the request (DNS, connect, TLS, request — Chapter 5) while the old page is still on screen.
- Response and commit: headers arrive; the browser decides which renderer process gets the new document (Site Isolation, Chapter 8) and commits the navigation. The URL bar updates. From here on, the old page is gone.
- Parse: the renderer streams the HTML into the parser, building the DOM.
DOMContentLoaded: fires when the parser finishes the document and alldeferand module scripts have run. The DOM is complete. Images may still be loading.load: fires when every subresource the page knew about at parse time — images, stylesheets, iframes, scripts — has finished.- Later:
pagehide/visibilitychangewhen the user leaves (more reliable thanunload, which is deprecated and blocks bfcache).
Neither DOMContentLoaded nor load is what users feel. Users feel first paint, the largest paint, and whether the page responds (Chapter 16). But these events are still useful landmarks in a trace.
The HTML parser
Section titled “The HTML parser”The parser reads bytes, decodes them to characters (using the declared charset — put <meta charset="utf-8"> in the first 1,024 bytes so it never has to restart), tokenizes them into tags, and builds the DOM tree incrementally. It’s forgiving by design: HTML’s parsing algorithm specifies exactly how to recover from every malformed input, which is why <p>unclosed still works.
Crucially, the parser is incremental: it doesn’t wait for the whole document. As soon as the first chunk arrives, it starts building, and the browser can render what it has — which is why streaming HTML (Chapter 7) works and why putting important content early in the document matters.
Render-blocking CSS
Section titled “Render-blocking CSS”CSS is render-blocking: the browser won’t paint the page until it has downloaded and parsed all the stylesheets in the <head> (more precisely, those that apply to the current media). Why? Because painting unstyled HTML and then repainting it when the CSS arrives would be a horrible flash of unstyled content (FOUC) and wasted work.
Consequences:
- Every byte of CSS in the head delays first paint. A 200 KB framework stylesheet on a slow connection is a long wait for a white screen.
- CSS from another origin costs a new connection (DNS + TCP + TLS) before it even starts downloading.
@importinside CSS is a waterfall: the browser only discovers the imported file after downloading and parsing the first one.- Stylesheets for other media (
media="print") download but don’t block rendering.
The classic optimization is critical CSS: inline the small amount of CSS needed for above-the-fold content directly in the HTML, and load the rest without blocking. Useful, with caveats (Chapter 18): inlined CSS isn’t cached separately, and getting “critical” right is fiddly. For most sites, simply keeping total CSS small and same-origin gets you most of the win.
Parser-blocking scripts
Section titled “Parser-blocking scripts”A classic script — <script src="app.js"></script>, no attributes — blocks the parser. When the parser meets it, it must:
- stop building the DOM,
- download the script (if not already downloaded),
- wait for any pending stylesheets (because the script might ask for computed styles!),
- execute the script,
- then resume parsing.
Why so strict? Because a classic script can call document.write(), injecting HTML that changes everything after it. The parser can’t safely continue without knowing what the script will do. It’s a 1990s design decision that still governs every page.
So a <script> in the <head> without attributes means: no DOM, no paint, nothing, until it’s downloaded and run. Put three of them there on Priya’s connection and you’ve added several hundred milliseconds of blank screen.
async, defer, type="module"
Section titled “async, defer, type="module"”Three attributes change the rules:
defer— download in parallel with parsing; execute after the document is fully parsed, in document order, beforeDOMContentLoaded. Doesn’t block parsing.async— download in parallel; execute as soon as it arrives, interrupting the parser at that moment; no ordering guarantee. Good for independent scripts (analytics) that don’t need the DOM complete or other scripts.type="module"— ES modules are deferred by default. Addasyncto make a module execute as soon as it and its imports are ready.
Where to put tags, then?
- Stylesheets: in the
<head>, as few and as small as possible, same-origin. - Your app scripts: in the
<head>withdefer(ortype="module"). They’re discovered early and fetched in parallel, and they don’t block parsing. (The old advice “put scripts at the end of<body>” was a workaround for the lack ofdefer; withdefer, head placement is better because discovery is earlier.) - Independent third-party scripts:
async, or better, loaded after the page is interactive.
The preload scanner: the hero nobody mentions
Section titled “The preload scanner: the hero nobody mentions”Back to the runner. When the main parser is blocked — waiting on a script, or busy executing one — a secondary, lightweight parser called the preload scanner races ahead through the raw HTML that has arrived but not yet been parsed. It doesn’t build a DOM. It just looks for things to fetch: <link rel="stylesheet">, <script src>, <img src> and srcset, <link rel="preload">, fonts and so on. It sends those requests immediately.
This means that by the time the main parser reaches the fourth image, it’s often already downloaded. On a high-latency connection, this parallelism is worth seconds.
The preload scanner can only find what is in the HTML markup. It cannot see:
- images set by JavaScript (
img.src = …), - elements rendered by a client-side framework (the entire page in CSR!),
- CSS
background-imageURLs (those are only discovered after the CSS is parsed and the element is styled), - fonts (discovered only when the CSS is parsed and text needs them),
- anything injected by
document.writeor added after load, - images marked
loading="lazy"(deliberately deferred).
Resource hints and priorities
Section titled “Resource hints and priorities”When markup alone isn’t enough, you can give the browser hints.
<link rel="preconnect" href="https://cdn.example">— open the connection (DNS + TCP + TLS) to an origin now, because we’ll need it soon. Saves round trips for critical third-party origins. Don’t preconnect to ten origins: each holds a socket and competes for early bandwidth.<link rel="dns-prefetch" href="…">— just the DNS lookup. Cheaper, weaker.<link rel="preload" href="hero.avif" as="image">— fetch this specific resource now, at high priority, for this page. For late-discovered critical resources: fonts, the LCP image when it’s a CSS background, a critical script imported by another script. Preloading things you don’t use within a few seconds wastes bandwidth (Chrome warns in the console).<link rel="modulepreload">— preload an ES module and its parse, avoiding module-graph waterfalls.<link rel="prefetch">— fetch something likely needed for the next navigation, at low priority, into the HTTP cache.- Speculation Rules — a JSON block (
<script type="speculationrules">) that tells Chromium-based browsers to prefetch or even fully prerender likely next pages — load and render them in a hidden tab, so clicking is instant. Rules can list URLs or match links in the document, with an eagerness setting (e.g., prerender on hover vs. immediately). Prerendering costs memory, bandwidth and server load, and runs your page’s code before the user arrives, so analytics must handle it.
Priorities and fetchpriority
Section titled “Priorities and fetchpriority”The browser assigns every request a priority: CSS in the head and blocking scripts are highest; images start low and are boosted when they turn out to be in the viewport; async scripts and prefetches are low. You can see the priority column in DevTools’ Network panel.
fetchpriority="high" on an <img> (or a <link rel="preload">) tells the browser “this image matters more than you’d guess” — ideal for the LCP hero, which otherwise starts at low priority until layout reveals it’s in the viewport. fetchpriority="low" demotes things like below-the-fold carousels.
Lazy loading
Section titled “Lazy loading”loading="lazy" on images and iframes defers fetching until they’re near the viewport. Excellent for below-the-fold content; a well-known mistake when applied to the hero image, which then can’t be fetched until layout has happened (and the preload scanner ignores it). Rule: never lazy-load the LCP image. Many frameworks’ image components lazy-load by default — check what yours does above the fold.
The back/forward cache (bfcache)
Section titled “The back/forward cache (bfcache)”When Priya taps Back, the fastest possible thing is to show the page she just left, exactly as it was — scroll position, form state, JS heap and all — without reloading anything. That’s the bfcache: browsers keep recently-left pages frozen in memory, and restore them instantly on back/forward navigation. Safari and Firefox have had it for many years; Chrome shipped it broadly around 2021.
A page restored from bfcache gets a pageshow event with event.persisted === true (useful to refresh stale data). A page is not eligible for bfcache if, for example, it has an unload handler, has open connections that can’t be paused (some WebSocket/WebRTC cases), or — historically in Chrome — was served with Cache-Control: no-store (Chrome has been relaxing this for some cases). DevTools’ Application panel has a “Back/forward cache” test that tells you exactly why a page isn’t eligible.
Back/forward navigations are a large fraction of all navigations on mobile. Making your pages bfcache-eligible is one of the cheapest big wins in web performance.
What you now know
Section titled “What you now know”You can walk the navigation lifecycle and say what each event means (and doesn’t); explain render-blocking CSS and parser-blocking scripts from first principles; choose between async, defer and modules; explain the preload scanner and what hides from it; apply preconnect, preload, prefetch, Speculation Rules, fetchpriority and lazy loading correctly; and make pages bfcache-friendly. That’s most of loading performance.
Self-quiz
Section titled “Self-quiz”1. Why does a classic script block the parser?
It might call document.write or otherwise change the document the parser is building, so the parser must wait for it.
2. Why does CSS block rendering but not parsing?
Painting before CSS would show unstyled content and then repaint; parsing can continue safely since CSS doesn’t change the DOM.
3. Name three things the preload scanner can’t see.
JS-inserted images, CSS background images, fonts, framework-rendered content, lazy images.
4. When should you use preload vs prefetch?
Preload: critical resources for the current page discovered late. Prefetch: likely resources for the next navigation, low priority.
5. Name two things that make a page ineligible for bfcache.
An unload handler; certain open connections; (historically) Cache-Control: no-store in Chrome.
Exercises
Section titled “Exercises”Warm-up 1. Order of execution. A head contains <script defer src=a>, <script async src=b>, <script defer src=c>. In what order can they run?
Solution
a then c (deferred, in order, after parsing). b whenever it arrives — possibly before, between or after them.
Warm-up 2. Spot the late hero. The LCP image is <div class="hero" style="background-image:url(hero.jpg)">. What’s wrong and how do you fix it?
Solution
Discovered only after CSS/style; invisible to the preload scanner. Use an <img> with fetchpriority="high", or add <link rel="preload" as="image" fetchpriority="high">.
Warm-up 3. Read the priority column. Why might the hero <img> start at “Low” priority and later become “High”?
Solution
Images start low; once layout shows the image is in the viewport, the browser boosts it. fetchpriority="high" skips the wait.
Lab 4. Lumen’s waterfall. Record Lumen’s essay page load at a Slow-4G-like throttle. Identify every request discovered late (started after the HTML finished).
Hint
The Network panel’s “Initiator” column shows who requested each resource. Anything initiated by a script or by CSS is a discovery problem.
Lab 5. Fix the hero. Make Lumen’s hero image discoverable and high priority. Measure LCP before and after under the same throttle.
Expected outcome
The hero request starts near the HTML; LCP improves by the discovery delay you removed.
Lab 6. bfcache audit. Run the bfcache test in DevTools on Lumen’s pages. Fix any blocking reasons.
Expected outcome
“Successfully served from back/forward cache.” Common fix: replace unload with pagehide.
Lab 7. Prerender the next essay. Add Speculation Rules to prerender essay links on hover (moderate eagerness). Navigate and compare.
Expected outcome
In Chromium browsers, hovered essays open instantly. Check the Application panel’s speculative loads section to see what was prerendered.
Staff 8. The marketing tags. Marketing wants five tags added to <head> as classic scripts “so they load first.” Write the response with a compromise.
Model answer
Classic head scripts block parsing and delay every metric for every user. Offer: async loading, after-interactive loading via a tag manager with a budget, or server-side alternatives; quantify the cost with a before/after trace.