Sub topic 12
Parsing HTML into the DOM
This chapter assumes you know the HTTP response from the previous chapters. It also assumes you can read basic HTML and JavaScript. It covers what the browser does with the HTML bytes in the response body.
From bytes to a tree
The response body arrives as bytes. The browser turns them into a tree of objects called the Document Object Model (DOM). JavaScript can read and change this tree. The work happens in four steps:
- Decode. The bytes become characters, using the encoding from the
Content-Typeheader or a<meta charset>tag. - Tokenize. The characters become tokens such as start tag, end tag, text and comment.
- Build nodes. Each token becomes an object, such as an element or text node.
- Attach. The parser inserts each node into the tree under its parent.
The parser is incremental. It does not wait for the whole file. It starts as soon as the first chunk arrives, so the DOM grows while the download continues.
A worked example
Take the page from earlier in the tutorial:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="/style.css">
<script src="/app.js" defer></script>
</head>
<body>
<h1>Hello</h1>
<img src="/logo.png" alt="Logo">
</body>
</html>The parser produces html with two children, head and body. Under head are link and script. Under body are h1, which has a text node "Hello", and img. The whitespace between tags also becomes text nodes. You can check the tree from the console:
const body = document.body;
console.log(body.children.length); // 2 (h1 and img)
console.log(body.childNodes.length); // more, because whitespace is text nodes
console.log(document.readyState); // 'loading', 'interactive' or 'complete'Scripts and parser blocking
A plain <script src> stops the parser. The script might call document.write() or change the tree, so the browser must fetch and run it first. A slow script therefore delays everything after it.
| Attribute | Fetching | Runs | Blocks parser |
|---|---|---|---|
| none | Fetched when reached | Immediately | Yes |
| `defer` | In parallel | After parsing, in document order | No |
| `async` | In parallel | As soon as downloaded | Only while running |
Use defer for scripts that need the DOM. Use async for independent scripts, such as analytics.
A script can also be held up by CSS. The browser waits for pending stylesheets before it runs a script, because the script may read computed styles. The CSS therefore also delays the parser, even though CSS is not parsed into the DOM.
While the parser waits on a script, the browser keeps scanning ahead. A lightweight preload scanner reads the remaining markup and starts downloading stylesheets, scripts and images early.
Common errors
- Script runs before the element exists. A script in
<head>withoutdefercallsdocument.querySelector('h1')and getsnull. Adddefer, or move the script to the end ofbody. - Expecting the DOM to match the source. The parser fixes mistakes. A missing
<tbody>is added, and misnested tags are rearranged. Always inspect the live DOM, not the source. - Confusing the DOM with the HTML file. Scripts change the DOM after parsing, so "View Source" and the Elements panel can differ.
- Mixing up load events.
DOMContentLoadedfires when parsing is finished and deferred scripts have run.loadfires later, after images and other subresources finish.
Exercise
A page has <script src="/big.js"></script> in <head> and a large image in <body>. Why does the page stay blank for a long time, and which one-attribute change would most likely help?
Show answer
The script has no defer or async, so the parser stops at it until /big.js is downloaded and executed. Nothing after it is parsed, so the body is not built. Adding defer lets the download run in parallel while parsing continues, and the script runs after parsing is done.