Part 01 · How the Browser Works

Parsing HTML and CSS

DOMCSSOMPreload scannerRender tree

How bytes turn into the DOM and CSSOM, why the preload scanner runs ahead of the parser, and how both trees join into the render tree.

⏱ 6 min · Station 2 of 125

The problem

ShopLite's product page has an analytics script in <head>. One morning the analytics vendor is slow and takes 1.5 seconds to answer. The page doesn't break, but every product image now seems to arrive late, and the team blames the image CDN.

The CDN is fine. To see why, you need to know how the browser reads HTML: what it does while it waits for that script, and what it can't do.

The idea

The browser turns HTML bytes into the DOM (a tree of elements) and CSS into the CSSOM (a tree of rules). Together they become the render tree: the visible elements with their final styles.

The HTML parser works top to bottom and must stop at every plain <script>, because the script could change the document that comes after it. To avoid wasting that time, browsers run a second, lighter reader, the preload scanner, that skims ahead and starts downloading the files it can see.

How it works

  1. Bytes to tokens. The parser decodes bytes (UTF-8 usually) and splits them into tokens: start tag <img>, attribute src, text, end tag.
  2. Tokens to nodes. Each token becomes a DOM node and goes into the tree. This happens incrementally: the first part of the page can be in the DOM while the rest is still downloading.
  3. A <script> without async or defer pauses the parser. It must download (if external) and run before parsing continues, because it might call document.write or read the DOM so far.
  4. The preload scanner keeps going through the raw HTML during that pause. It doesn't build a DOM; it just looks for src and href in <link>, <script>, <img> and starts those requests early.
  5. CSS becomes the CSSOM. Stylesheets are parsed into rules. CSS doesn't block the HTML parser, but it does block rendering (and blocks scripts that come after it, since they might read styles).
  6. Render tree, then style. The browser combines DOM and CSSOM, drops invisible nodes (display: none, <head>), and works out each element's computed style (recalculate style). Layout comes next (Layout, Paint and Composite).

The scanner has a blind spot: anything that only exists after JavaScript runs. An image created with new Image(), a script injected by a tag manager, a background image inside a CSS file: none of these are in the HTML text, so none start early.

Predict first

parse.html has a script in <head> that takes 1500 ms, then a stylesheet and three <img> tags in <body>. When do the three images start downloading?

Visual

parse.htmlnetwork<script src="slow.js"><link href="late.css"><img src="1.svg"><img src="2.svg"><img src="3.svg"><script> new Image(4.svg)requestsin flightparserpreload scannercssimg 1img 2img 3slow.jsimg 4the parser must stop: slow.js might change the pagemeanwhile the preload scanner reads ahead and starts every file it can seemeasured: css and 3 images start at about 18 ms, long before the script arrivesthe parser resumes and runs the inline scriptimg 4 only exists after JavaScript runs: it starts at 1536 ms
The parser stops at a slow script. The preload scanner reads ahead and starts the CSS and three images; the fourth image only exists after JavaScript runs, so it starts last.

Who blocks what

ResourceBlocks the HTML parser?Blocks rendering?Found by the preload scanner?
<script src> (plain)yesyes (nothing after it is parsed)yes
<script defer> / type="module"no, runs after parsingnoyes
<script async>no, but pauses when it runsnoyes
<link rel="stylesheet">noyesyes
<img src>nonoyes
new Image() / injected <script>nonono
background-image in CSSnonono (found when the CSS is applied)
<link rel="preload">nonoyes, that's its job

See it live

Measured on an Intel i3-10110U laptop (4 threads), 7 GB RAM, Ubuntu 26.04, Chrome 151 headless via Playwright 1.64.1, the lab running in Docker on the same machine.

parse.html in the lab (web/public/x/):

<!doctype html>
<html>
<head>
  <title>preload scanner</title>
  <!-- a slow script in the head: the parser must stop here for 1.5 s -->
  <script src="http://localhost:4000/asset/slow.js?latency=1500&kb=1"></script>
  <link rel="stylesheet" href="http://localhost:4000/asset/late.css?kb=5" />
</head>
<body>
  <h1>Product page</h1>
  <img src="http://localhost:4000/img/1.svg" width="200" height="150" />
  <img src="http://localhost:4000/img/2.svg" width="200" height="150" />
  <img src="http://localhost:4000/img/3.svg" width="200" height="150" />
  <script>
    // An image added by JavaScript: no scanner can see it in the HTML.
    const i = new Image(200, 150);
    i.src = "http://localhost:4000/img/4.svg";
    document.body.append(i);
  </script>
</body>
</html>

tools/parse.mjs loads it and reads each request's start time from Resource Timing. Then it loads big.html (1.6 MB: 10,000 product cards and 2,000 CSS rules) with a 4x slower CPU and records a performance trace to see what parsing costs:

// node parse.mjs: two experiments on how HTML and CSS get parsed.
import { open, trace, mainThreadSummary, pageTimings, resources, WEB, ms } from "./lib.mjs";

// 1. The preload scanner. parse.html has a 1.5 s script in <head>. When does each file start?
{
  const { browser, page } = await open();
  await page.goto(`${WEB}/x/parse.html`, { waitUntil: "networkidle" });
  const rows = await resources(page);
  const t = await pageTimings(page);
  await browser.close();
  console.log("1) parse.html: a 1500 ms script blocks the parser in <head>\n");
  console.log("request                     starts at   found by");
  for (const r of rows.filter((r) => !r.name.includes("favicon"))) {
    const name = r.name.split("?")[0];
    const by = name.endsWith("4.svg") ? "JavaScript, after the parser resumed" : name.endsWith("slow.js") ? "parser" : "preload scanner";
    console.log(`${name.padEnd(26)} ${ms(r.start).padStart(9)}   ${by}`);
  }
  console.log(`\nparser reached the end of <body> (domInteractive): ${ms(t.domInteractive)}`);
}

// 2. What parsing costs. big.html: 1.6 MB, 10,000 product cards and 2,000 CSS rules.
{
  const { browser, page } = await open({ cpu: 4 });
  const events = await trace(browser, page, () => page.goto(`${WEB}/x/big.html`, { waitUntil: "load" }));
  const nodes = await page.evaluate(() => document.getElementsByTagName("*").length);
  const t = await pageTimings(page);
  await browser.close();
  const s = mainThreadSummary(events, ["ParseHTML", "UpdateLayoutTree", "Layout", "PrePaint", "Paint"]);
  const label = { ParseHTML: "parse HTML (+ inline CSS)", UpdateLayoutTree: "recalculate style", Layout: "layout", PrePaint: "pre-paint", Paint: "paint" };
  console.log("\n2) big.html: 10,000 cards, 2,000 CSS rules, CPU throttled 4x\n");
  console.log("main-thread step            calls   total");
  for (const [k, v] of Object.entries(s)) console.log(`${label[k].padEnd(26)} ${String(v.count).padStart(6)} ${ms(v.ms).padStart(8)}`);
  console.log(`\nelements in the DOM: ${nodes}`);
  console.log(`first contentful paint: ${ms(t.fcp)}   DOMContentLoaded: ${ms(t.dcl)}`);
}
1) parse.html: a 1500 ms script blocks the parser in <head>

request                     starts at   found by
/asset/slow.js                 17 ms   parser
/asset/late.css                18 ms   preload scanner
/img/1.svg                     19 ms   preload scanner
/img/2.svg                     20 ms   preload scanner
/img/3.svg                     20 ms   preload scanner
/img/4.svg                   1536 ms   JavaScript, after the parser resumed

parser reached the end of <body> (domInteractive): 1575 ms

2) big.html: 10,000 cards, 2,000 CSS rules, CPU throttled 4x

main-thread step            calls   total
parse HTML (+ inline CSS)      10   347 ms
recalculate style               9  1050 ms
layout                          8  1992 ms
pre-paint                       8   621 ms
paint                           8    40 ms

elements in the DOM: 50006
first contentful paint: 440 ms   DOMContentLoaded: 1565 ms

Reading part 1:

  • The CSS and the three images started at 18-20 ms, right next to the script (17 ms), even though the parser was stuck on that script until about 1.5 s. The preload scanner found them.
  • 4.svg started at 1536 ms. It's created by JavaScript, so it had to wait for the slow script to arrive, the parser to resume, and the inline script to run. Same server, same file size: about 1.5 s later.
  • domInteractive at 1575 ms is when the parser finally reached the end. Everything the scanner found was already downloaded by then.

Reading part 2 (10,000 cards, 50,006 elements, 4x CPU):

Main-thread stepTime
Parse HTML (+ the inline CSS)347 ms over 10 chunks
Recalculate style1050 ms
Layout1992 ms
Pre-paint + paint661 ms
  • Parsing is the cheap part. 1.6 MB of HTML parsed in 347 ms, in 10 chunks, so the first chunk painted at 440 ms (FCP) while the rest was still parsing.
  • What the DOM costs comes after parsing: matching 2,000 rules against 50,000 elements, then laying them all out, took almost 9 times longer than reading the bytes. A huge DOM is expensive because of style and layout, not because of the parser.

In real apps

  • Third-party scripts go async or defer. Tag managers, analytics and chat widgets are the most common parser blockers on e-commerce sites.
  • Make important resources visible in HTML. The product hero image as a real <img> (not a CSS background or a JS-created image), or a <link rel="preload" as="image"> for it.
  • Keep the DOM small. Feeds and listings render only what's on screen (list virtualization, Part 7), because 10,000 cards cost seconds of style and layout on a slow phone.
  • Stream the HTML. Servers that flush the <head> early let the scanner start CSS and fonts before the page body is even ready (streaming SSR, Part 6).

What goes wrong in production

  • A slow vendor script in <head> delays the whole page, and the delay looks like something else (late images, late fonts).
  • LCP image discovered late because it's a CSS background or set by JavaScript after hydration: hundreds of milliseconds of LCP lost on mobile.
  • document.write from old ad scripts inserts scripts the scanner can't see and stops the parser for each one; on 2G connections Chrome refuses to run cross-origin scripts inserted this way.
  • Giant server-rendered pages (every product and every filter in the HTML) parse fast and then spend seconds in style and layout.

Key takeaway

The parser stops at plain scripts; the preload scanner keeps fetching what it can see in the HTML text. Make important files visible to the scanner, keep blocking scripts out of <head>, and remember that a big DOM costs more in style and layout than in parsing.

Practice

Change the stylesheet in parse.html to load its fonts with @font-face { src: url(...) } and use them on the <h1>. Predict: does the preload scanner start the font file early, along with the CSS? Then check the start times with node parse.mjs.

Answer

No. The scanner only reads HTML. The font URL is inside the CSS, and the browser only requests a font when the CSSOM is built and an element on the page needs that font, so it starts after the CSS has downloaded and been applied: one extra wave. That's why sites add <link rel="preload" as="font" type="font/woff2" crossorigin href="..."> for the one or two fonts the first screen needs. (Bangla fonts are large, which makes this matter even more; Part 7 measures it.)

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.

Go Pro to earn XP →