Sub topic 12
Parsing HTML into the DOM
This chapter assumes you know basic HTML syntax, what a browser's network request returns, and how HTTP responses carry a body. It covers what the browser does with the bytes of an HTML response before any pixels appear.
From bytes to tokens to nodes
The server sends bytes, not text. The browser turns them into a Document Object Model (DOM), a tree of objects that JavaScript and CSS can work with. The path has four steps:
- Bytes to characters. The browser picks a character encoding. It checks the
Content-Typeheader (for examplecharset=utf-8), then a byte order mark, then a<meta charset>tag in the first bytes of the document. If nothing says otherwise, it guesses. - Characters to tokens. The tokenizer reads characters and emits tokens such as start tag, end tag, character data and comment.
- Tokens to nodes. The tree builder consumes tokens and creates objects: elements, text nodes and comments.
- Nodes to a tree. Each new node is attached to its parent, which gives the DOM.
The parser is incremental. It does not wait for the full response. It processes bytes as they arrive from the TCP connection, so the DOM grows while the download is still in progress. This is why a long page can start to show content before it has fully loaded.
A worked example
Use the page from the topic's earlier example:
<!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 tree builder produces this structure:
Document
└── html
├── head
│ ├── link (rel=stylesheet)
│ └── script (defer)
└── body
├── h1
│ └── "Hello"
└── img (alt=Logo)Whitespace between tags also becomes text nodes in the real DOM. The tree above hides them for readability. You can see them in the console:
const body = document.body;
console.log(body.childNodes.length); // includes whitespace text nodes
console.log(body.children.length); // elements only: 2childNodes returns every node. children returns only elements. Mixing them up is a common source of off-by-one bugs.
The parser is forgiving
HTML is not XML. A parse error does not stop the page. The HTML specification defines exactly how to recover from every kind of malformed input, so all modern browsers build the same tree from the same broken markup.
Some examples of recovery:
- A missing
<html>,<head>or<body>is added automatically. - A
<p>is closed when a new block element such as another<p>or a<div>begins. - Unclosed
<li>elements are closed when the next<li>appears. - Text placed directly inside a
<table>is moved out in front of the table ("foster parenting").
Check this yourself:
const doc = new DOMParser().parseFromString('<p>One<p>Two', 'text/html');
console.log(doc.body.innerHTML); // <p>One</p><p>Two</p>
console.log(doc.documentElement.outerHTML);
// <html><head></head><body><p>One</p><p>Two</p></body></html>The result is a complete document with head and body, even though the input was two unclosed paragraphs.
Scripts and parser blocking
JavaScript can change the document while it is being parsed, for example with document.write(). For that reason a classic script blocks the parser by default.
When the parser meets <script src="/app.js"></script> with no attributes:
- The parser pauses.
- The browser fetches the script (if not cached).
- The script runs.
- The parser resumes.
Nothing after the script tag is added to the DOM until these steps finish. A slow script stalls the whole page.
A script can also be blocked by CSS. Scripts may read styles, such as getComputedStyle(). So the browser waits for pending stylesheets to load before it runs a script. A slow stylesheet followed by a script therefore delays everything after both.
Three attributes change this behavior:
| Attribute | Fetch | Execution | Order kept | Typical use |
|---|---|---|---|---|
| none | Blocks the parser | Immediately after the fetch | Yes | Legacy code that uses `document.write` |
| `defer` | In parallel with parsing | After parsing ends, before `DOMContentLoaded` | Yes | Application code that needs the DOM |
| `async` | In parallel with parsing | As soon as it arrives | No | Independent scripts such as analytics |
Module scripts (type="module") behave like defer by default. Both defer and async apply only to scripts with a src. Inline scripts always run immediately.
The preload scanner
If the main parser stops at a blocking script, the browser would normally wait before it discovers the images and stylesheets further down the page. To avoid that, browsers run a second, lightweight scanner ahead of the main parser. This preload scanner reads the raw markup, finds URLs in tags like <link>, <script> and <img>, and starts those downloads early.
The scanner cannot see resources that only appear after JavaScript runs. That includes images inserted by script and CSS background-image URLs, because the scanner does not evaluate CSS or JavaScript. Resources that matter for the first paint are better placed in plain HTML tags, or hinted with <link rel="preload">.
Events that mark progress
The parser reports its progress through two events and one property.
| Signal | When it fires |
|---|---|
| `document.readyState === 'loading'` | The parser is still working |
| `DOMContentLoaded` | The HTML is fully parsed and deferred scripts have run. Stylesheets, images and subframes may still be loading |
| `document.readyState === 'interactive'` | The parser has finished, just before `DOMContentLoaded` |
| `load` | The page and all its subresources, such as images and stylesheets, have finished loading |
You can log the order:
console.log('start:', document.readyState);
document.addEventListener('readystatechange', () => {
console.log('readyState:', document.readyState);
});
document.addEventListener('DOMContentLoaded', () => {
console.log('DOMContentLoaded');
});
window.addEventListener('load', () => {
console.log('load');
});Typical output for a normal page is start: loading, readyState: interactive, DOMContentLoaded, readyState: complete, load.
Common errors
- Reading the DOM too early. A classic script in
<head>runs before<body>exists, sodocument.getElementById('app')returnsnull. Usedefer, move the script to the end of<body>, or wait forDOMContentLoaded. - Missing charset. Without a declared encoding the browser may guess wrong and show garbled text. Declare
<meta charset="utf-8">within the first 1024 bytes, or send the charset in theContent-Typeheader. - Missing doctype. Without
<!doctype html>the browser uses quirks mode, which changes some layout rules. Always start with the doctype. - Expecting source to equal DOM. Invalid nesting such as a
<div>inside a<p>closes the paragraph early. The DOM then differs from what you wrote. - Using
asyncfor dependent scripts. Twoasyncscripts can run in either order. If one needs the other, usedefer. - Using
innerHTMLwith untrusted text. It runs the HTML parser on the string, so attacker-controlled markup becomes real elements. UsetextContentfor plain text.
Why this stage matters for speed
The DOM alone draws nothing. The next chapters turn it into pixels, but parsing already shapes performance:
- Every blocking script adds a network round trip and execution time before the rest of the page is parsed.
- Every stylesheet in
<head>delays rendering and may delay scripts that follow it. - A large DOM costs memory and slows later style and layout work. Pages with tens of thousands of nodes are a common cause of sluggishness.
You can measure parse timing for the current page using the Navigation Timing API:
const [nav] = performance.getEntriesByType('navigation');
console.log('Response end ms:', nav.responseEnd);
console.log('DOM interactive ms:', nav.domInteractive);
console.log('DOMContentLoaded ms:', nav.domContentLoadedEventEnd);
console.log('Load ms:', nav.loadEventEnd);The gap between responseEnd and domInteractive is roughly the time spent parsing and running blocking scripts after the HTML finished arriving.
Exercise
A page has <script src="/a.js"></script> in <head>, and a.js calls document.querySelector('h1').textContent = 'Hi'. The <h1> is in <body>. Why does this throw an error, and name two ways to fix it without moving the h1.
Show answer
The classic script runs as soon as it is fetched, and the parser pauses at that point. The <body> and <h1> have not been parsed yet, so querySelector returns null and setting textContent on it throws a TypeError. Two fixes: add defer to the script tag so it runs after parsing finishes, or wrap the code in a DOMContentLoaded listener. Moving the script to the end of <body> also works.
Exercise
You load a page whose HTML contains <p>First<p>Second and then inspect it in the Elements panel. How many p elements do you see, and why is the result the same in every modern browser?
Show answer
Two p elements. The HTML specification defines error recovery: a new <p> start tag implicitly closes an open <p>. Because the recovery rules are part of the specification, all browsers build the same tree from the same invalid markup.
Exercise
A page includes two scripts with async: lib.js and plugin.js. plugin.js needs a global defined by lib.js. It works on your fast connection but fails for some users. What is the cause and the fix?
Show answer
async scripts run as soon as each one arrives, in no guaranteed order. On a slow connection plugin.js can arrive and run before lib.js. Use defer on both, which keeps document order, or bundle the two files.