Skip to content

9. Loading a Page — The Critical Rendering Path

“The fastest request is the one the browser started before you asked.”

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.

From Priya’s tap to a fully loaded page, a navigation passes through these moments:

  1. beforeunload on 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.)
  2. Network: the browser process makes the request (DNS, connect, TLS, request — Chapter 5) while the old page is still on screen.
  3. 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.
  4. Parse: the renderer streams the HTML into the parser, building the DOM.
  5. DOMContentLoaded: fires when the parser finishes the document and all defer and module scripts have run. The DOM is complete. Images may still be loading.
  6. load: fires when every subresource the page knew about at parse time — images, stylesheets, iframes, scripts — has finished.
  7. Later: pagehide/visibilitychange when the user leaves (more reliable than unload, 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.

Navigation lifecycleA timeline: beforeunload on the old page, network request, commit, parsing builds the DOM, first contentful paint, DOMContentLoaded after deferred scripts, then load after images and subresources finish.before­unloadnetwork (old page visible)commitparse → DOMFCPDOMContentLoadedloadWhat users feel (FCP, LCP, INP) is not the same as what events report (DCL, load).
Figure 9.1. The navigation lifecycle. The old page stays visible until commit (Chrome's 'paint holding' keeps it there briefly afterwards to avoid a white flash). Events fire in a fixed order; what the user feels sits between them.

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.

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.
  • @import inside 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.

A classic script — <script src="app.js"></script>, no attributes — blocks the parser. When the parser meets it, it must:

  1. stop building the DOM,
  2. download the script (if not already downloaded),
  3. wait for any pending stylesheets (because the script might ask for computed styles!),
  4. execute the script,
  5. 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.

Three attributes change the rules:

  • defer — download in parallel with parsing; execute after the document is fully parsed, in document order, before DOMContentLoaded. 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. Add async to make a module execute as soon as it and its imports are ready.
Script loading modesFour rows each showing parsing in green, fetching in blue, and execution in yellow. Classic script: parsing stops while the script is fetched and executed, then resumes. Defer: parsing continues while fetching; execution happens after parsing completes. Async: parsing continues while fetching; execution interrupts parsing when the script arrives. Module: like defer by default.<script>fetchrunparser STOPPEDdeferrunfetched in parallel, runs after parse, in orderasyncrunruns whenever it arrives (pauses parser)modulerun= defer
Figure 9.2. Classic vs. defer vs. async vs. module. The difference is entirely about whether the parser stops, and when execution happens.

Where to put tags, then?

  • Stylesheets: in the <head>, as few and as small as possible, same-origin.
  • Your app scripts: in the <head> with defer (or type="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 of defer; with defer, 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-image URLs (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.write or added after load,
  • images marked loading="lazy" (deliberately deferred).
Preload scanner timelineThree lanes over time. Main parser: parses the head, blocks on a script, then resumes. Preload scanner: during the block, it scans ahead and discovers CSS, a script and two images, launching fetches immediately. Network: the discovered resources download in parallel. A hero image set as a CSS background is only discovered much later after styles are computed, shown in red.Main parserparseblocked on scriptparse restPreload scannerscan ahead → fetch!Networkstyle.cssapp.jsimg 1, img 2 (found early)CSS background hero →
Figure 9.3. The parser and its scout. While the main parser is blocked on a script, the preload scanner reads ahead and starts fetching resources it finds in the markup. Anything not in the markup — JS-inserted images, CSS backgrounds, fonts — is discovered late.

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.

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.

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.

Effect of resource hintsBefore: HTML, then CSS, then font discovered from CSS, then hero image discovered late after layout, ending around 2.8 seconds. After: HTML with preload and fetchpriority high lets CSS, font and hero start almost together, ending around 1.6 seconds.BeforeHTMLCSSfonthero (discovered late)AfterHTMLCSSfont (preload)hero (fetchpriority=high)
Figure 9.4. The same page with and without hints. Preconnect, preload and fetchpriority pull the LCP image's request forward by hundreds of milliseconds on a high-latency connection.

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.

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.

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.

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.