Sub topic 11
From HTML response to rendered page
This chapter follows the bytes of an HTML response from the network into pixels on screen. It assumes you can read an HTTP response (status line, headers, body), know what a URL is, and have written basic HTML and CSS. Servers and caching appear only where they affect rendering.
The pipeline at a glance
A browser does not wait for the whole response before it starts working. It parses the HTML while the bytes arrive, discovers more resources as it goes, and requests them in parallel. Each of those requests is another HTTP exchange like the one that delivered the HTML.
Decoding the bytes
The first step is deciding how to turn bytes into characters. The browser checks these sources in order:
- A byte order mark at the start of the body.
- The
charsetparameter of theContent-Typeheader, for exampletext/html; charset=utf-8. - A
<meta charset="utf-8">tag near the top of the document. - A heuristic guess, if none of the above is present.
Always send the charset in the header. If the browser has to guess, or finds the <meta> tag late, it may restart parsing with a different encoding, and non-ASCII text can come out garbled.
The Content-Type header also decides whether the body is treated as HTML at all. The same bytes served as text/plain appear as literal source text.
Tokenizing and building the DOM
The HTML parser reads characters and emits tokens such as start tag, end tag, and text. It uses the tokens to build the Document Object Model (DOM), a tree of nodes that JavaScript can read and change.
HTML parsing is forgiving by specification. A missing </p>, a stray </div>, or a <td> outside a table does not produce an error. The spec defines exactly how to repair each case, so every browser produces the same tree. Because of this, the DOM you see in DevTools can differ from your source file.
The first line of the document also matters. Without <!DOCTYPE html>, browsers switch to quirks mode, which emulates old layout behavior. Always include the doctype.
Discovering subresources
When the parser meets <link rel="stylesheet">, <script src>, or <img src>, it resolves the URL against the document's URL (or a <base> tag) and starts a request. The browser also runs a lightweight preload scanner ahead of the main parser. It scans raw markup for resource URLs so downloads begin even while the main parser is stalled. This is why putting an image URL in a data-src attribute and setting src from JavaScript is often slower: the scanner cannot see it.
Subresource requests go through the normal HTTP machinery: cookies for that origin are attached, the cache is consulted, and connections are reused where the protocol allows.
CSS and the CSSOM
The browser parses CSS into the CSS Object Model (CSSOM), which holds every rule and its cascade order. Rendering needs the complete CSSOM, because a rule near the end of a stylesheet can override an earlier one. For this reason a stylesheet is render-blocking: the browser will not paint content that depends on styles it has not finished loading. This avoids a flash of unstyled content.
Scripts: parser-blocking by default
A classic script can change the document with document.write or by reading layout. So when the parser reaches a plain <script src>, it stops, downloads and runs the script, then resumes. A script also waits for any pending stylesheets, because it might query computed styles.
Two attributes change this:
| Attribute | Download | Execution | Order preserved |
|---|---|---|---|
| none | Blocks the parser | Immediately | Yes |
| `async` | In parallel | As soon as it arrives | No |
| `defer` | In parallel | After parsing finishes, before `DOMContentLoaded` | Yes |
| `type="module"` | In parallel | Deferred by default | Yes |
Use defer for scripts that depend on the DOM or on each other. Use async for independent scripts such as analytics.
Here is a complete page you can save and open to watch the order of events:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Load order demo</title>
<style>
body { font-family: sans-serif; }
#status { color: #0a6; }
</style>
<script defer>
console.log("deferred script ran, readyState:", document.readyState);
document.getElementById("status").textContent = "DOM is ready";
</script>
</head>
<body>
<h1>Load order demo</h1>
<p id="status">Waiting…</p>
<img src="https://example.com/missing.png" alt="" width="1" height="1">
<script>
console.log("inline script ran, readyState:", document.readyState);
document.addEventListener("DOMContentLoaded", () => console.log("DOMContentLoaded"));
window.addEventListener("load", () => console.log("load"));
</script>
</body>
</html>Open the browser console. The inline script logs loading, then DOMContentLoaded fires, then load. Note that the defer attribute is honored on external scripts only. On the inline script above it has no effect, so that script runs immediately and logs loading. Move the code to a separate .js file to see real deferral.
DOMContentLoaded versus load
DOMContentLoaded fires when the HTML is fully parsed and deferred scripts have run. It does not wait for images or stylesheets in most cases. The load event fires later, after all subresources (images, stylesheets, frames) have finished. Prefer DOMContentLoaded for initialization, since load can be delayed by one slow image.
Render tree, layout, paint, composite
Once the DOM and CSSOM exist, the browser combines them into a render tree. This tree holds only visible nodes, each with its computed style. Nodes with display: none and the <head> are excluded. Elements with visibility: hidden stay in the tree because they still occupy space.
The remaining stages are:
- Layout computes the size and position of every box. It depends on viewport width, so resizing the window triggers it again.
- Paint records what to draw for each box: text, borders, backgrounds, images.
- Composite combines painted layers, often on the GPU, into the final frame.
Changing width forces layout, paint, and composite. Changing background-color skips layout. Changing transform or opacity on a promoted layer can skip both layout and paint, which is why animations use them.
Why pages feel slow: common causes
- Large render-blocking CSS or synchronous scripts in
<head>. They delay first paint. - Images without
widthandheight. The layout shifts when they arrive, which hurts the Cumulative Layout Shift metric. - Script-injected resources. The preload scanner cannot see them.
- Long JavaScript tasks. The browser has one main thread for parsing, scripting, and layout, so a long task freezes the page.
Exercise
A page's <head> contains <script src="app.js"></script> and the page body is blank for two seconds. Name two changes that could improve the time to first paint, and say what each one changes about how the browser behaves.
Show answer
Add defer to the script (or move it to the end of <body>) so the parser no longer stops to download and run it, and the DOM and render tree can be built while the file downloads. Alternatively, add async if the script does not depend on the DOM or other scripts, so it downloads in parallel and runs when ready. Also check for large render-blocking stylesheets, since a script waits for pending CSS.
Exercise
You serve an HTML page with Content-Type: text/html (no charset) and a <meta charset="utf-8"> tag at the bottom of a long <head>. Why is this risky?
Show answer
The browser must decide the encoding before it knows about the meta tag. It reads only the first part of the file for a meta declaration, so a tag that appears late may be missed or force a re-parse with a different encoding, producing garbled non-ASCII text. Send charset=utf-8 in the Content-Type header and put the meta tag first in the <head>.