How a browser parses HTML into the DOM, CSS into the CSSOM, runs layout, paint and compositing, how scripts block parsing, and how the single-threaded event loop with tasks and microtasks schedules JavaScript.
The browser streams and parses the HTML into the DOM and parses CSS into the CSSOM. Together they form the render tree, which goes through layout (sizes and positions), paint (pixels per layer) and compositing (layers combined on the GPU). A plain <script> blocks the parser until it downloads and runs, which is why we use defer or type="module"; CSS is render-blocking. All page JavaScript runs on one main thread driven by the event loop: take one task (a click, a timer, a network callback), run it to completion, drain the microtask queue (promise continuations, await), then render if a frame is due. The trade-off to remember: anything that hogs the main thread, whether your script or a huge DOM the server sent, freezes both input and rendering.
"When my ASP.NET Core endpoint returns HTML, the browser doesn't wait for the whole response. It parses the bytes as they stream in, tokenises the markup and builds the DOM, a tree of nodes that JavaScript can query and change. Whenever it meets a stylesheet it fetches and parses it into the CSSOM. The browser won't paint until it has the CSS, because painting unstyled content and then restyling would flash, so CSS is render-blocking. It then combines DOM and CSSOM into a render tree of visible elements, runs layout to work out every box's geometry, paints each layer into pixels and composites the layers, usually on the GPU.
Scripts are the interesting part. A plain
<script src>stops the parser: the browser has to download and execute it, because the script might calldocument.writeor read the DOM so far. That's why modern pages usedeferortype=\"module\", which download in parallel and run after parsing finishes, in order. All of that JavaScript runs on a single main thread managed by the event loop: pick one task from a queue, such as a click handler, a timer or a fetch response, run it to completion, then run every microtask, which is where promise callbacks and code afterawaitlive, and then let the browser render a frame if one is due, roughly every 16 ms at 60 Hz.The mistake I see backend engineers make is assuming the browser is like a multi-threaded server. It isn't: one 300 ms loop over a big JSON payload blocks clicks, scrolling and painting for 300 ms. So the things I control on the server, like HTML size, how many DOM nodes I render, caching and compression headers, and whether scripts are deferred, directly decide how fast the page feels."
| Stage | Input | Output | What blocks it |
|---|---|---|---|
| Parse HTML | Byte stream | DOM | Synchronous <script> |
| Parse CSS | Stylesheets | CSSOM | Slow CSS download |
| Style | DOM + CSSOM | Computed styles / render tree | Large, complex selectors |
| Layout | Render tree | Box geometry | Forced synchronous layout from JS |
| Paint | Geometry + styles | Layer bitmaps | Expensive effects (shadows, filters) |
| Composite | Layers | Frame on screen | Too many layers |
| Attribute | Downloads | Runs | Order kept | Use for |
|---|---|---|---|---|
| none | Blocks parser | Immediately | Yes | Almost never now |
async |
In parallel | As soon as downloaded | No | Independent scripts (analytics) |
defer |
In parallel | After parsing, before DOMContentLoaded |
Yes | App scripts |
type="module" |
In parallel | Deferred by default | Yes | Modern bundles (Vite output) |
| Queue | Examples | When it runs |
|---|---|---|
| Task (macrotask) | Event handlers, setTimeout, MessageChannel, network callbacks |
One per loop turn |
| Microtask | Promise .then, code after await, queueMicrotask |
All of them, right after the current task |
| Render steps | requestAnimationFrame, style, layout, paint |
When a frame is due, between tasks |
An internal dashboard rendered a 12,000-row table server-side and loaded a 900 KB script without defer. First paint took 4.1 s on office laptops. Paginating to 100 rows, adding defer and enabling Brotli brought first paint to 0.9 s and the longest main-thread task from 1.2 s to 80 ms.
Checks that a backend engineer has a correct mental model of how the browser processes what the server sends, especially single-threaded JavaScript.
Green flags
defer/module changeawait continuations runRed flags
The HTML parser is a state machine defined by the WHATWG HTML spec. It is deliberately forgiving: unclosed tags and bad nesting are repaired by rules, not rejected. It works incrementally, so a server that flushes the <head> early (for example via streaming rendering) lets the browser start fetching CSS before the body arrives.
response bytes -> decoder (charset) -> tokenizer -> tree builder -> DOM
|
<link rel=stylesheet> +-> fetch CSS -> CSSOM
<script> +-> fetch + execute (blocks tree builder)
A preload scanner runs ahead of the main parser while it is blocked on a script and starts downloading images, CSS and scripts it can see. That's why a blocking script is bad but not catastrophic.
A script might read getComputedStyle, so the browser won't run a script until earlier stylesheets are parsed. A slow CSS file therefore delays both painting and script execution.
DOM + CSSOM
|
v
render tree (display:none elements excluded)
|
v
layout -> x, y, width, height for every box
|
v
paint -> draw commands per layer
|
v
composite -> GPU combines layers -> frame
Changing transform or opacity usually only needs compositing (cheap). Changing width or inserting nodes needs layout again (expensive). Reading offsetHeight right after a write forces a synchronous layout ("layout thrashing").
The browser's main thread loops roughly like this:
while (true) {
task = pickOldestTask() // click, timer, fetch callback, message
run(task) // to completion: no pre-emption
drainMicrotasks() // promise reactions, await continuations
if (frameDue) {
runAnimationFrameCallbacks() // requestAnimationFrame
style(); layout(); paint()
}
}
Compared with .NET: there is no thread pool for your page code. await in JavaScript is closer to await in a UI app with a SynchronizationContext: the continuation always comes back to the single main thread. Web Workers are the only way to run JS in parallel, and they cannot touch the DOM.
| Server decision | Effect in the browser |
|---|---|
| Response compression (Brotli/gzip) | Fewer bytes before parsing completes |
Cache-Control on static assets |
Repeat visits skip downloads |
| HTML size and DOM node count | Parse, style and layout time |
Script tags with defer/module |
Parser never blocked |
Link: rel=preload or early hints (103) |
Critical assets fetched sooner |
setTimeout(() => console.log('task')); Promise.resolve().then(() => console.log('microtask')); console.log('sync'); into the console and explain the order.<script> that sleeps 2 s, then add defer and compare first paint in the Performance panel.<script src> in the <head> without defer. Why it is wrong: It stops the parser until the script downloads and runs. Instead: Use defer or type="module".setTimeout(fn, 0) runs before a resolved promise callback. Why it is wrong: Promise reactions are microtasks and run before the next task. Instead: Learn the task/microtask order.offsetHeight, getBoundingClientRect) inside a loop that also writes styles. Why it is wrong: Each read after a write forces the browser to recalculate style and layout synchronously, again and again: this is layout thrashing, and it can turn a 2 ms loop into 200 ms. Instead: Batch all reads first, then all writes (or write inside requestAnimationFrame).A backend engineer doesn't need to master rendering internals, but they own several of its inputs: bytes on the wire, cacheability, HTML shape and how quickly the first byte arrives. Most "the frontend is slow" investigations I've seen end at something the server could fix: an uncompressed 2 MB JSON blob, no-store on hashed assets, or a page that renders thousands of nodes nobody scrolls to.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Server-rendered HTML (Razor, Blazor static SSR) | Content pages, forms, fast first paint | Server CPU per request | Highly interactive canvases |
| SPA (React/Angular) with JSON API | Rich interaction after load | Bigger JS bundle, slower first load | Mostly static content |
| Streaming/early flush | Slow data, want fast <head> |
More complex error handling | Responses that must fail atomically |
Measure with the Performance panel and Lighthouse locally, and with real-user monitoring (Application Insights browser SDK or Core Web Vitals in the field) in production; lab numbers on a fast laptop hide what mobile users in regional Australia see.
An HTTP message has three parts: a start line, headers and an optional body. A request's start line is the method, target and version (GET /orders/42?include=lines HTTP/1.1); a response's is the status line (HTTP/1.1 200 OK). Headers carry metadata such as Content-Type, Accept and Authorization; a blank line separates them from the body.
In an API, the route identifies the resource, the query string filters or shapes it, headers carry cross-cutting metadata, and the body carries the representation being created or changed. ASP.NET Core exposes all of this through HttpContext.Request and HttpContext.Response, and model binding maps it onto parameters. The trade-off: URLs are logged and cached everywhere, so anything sensitive goes in headers or the body, never the query string.
A Web Worker runs a script on a separate thread with its own event loop. It can't touch the DOM; it talks to the page with postMessage (structured clone or transferable objects). Use it for CPU-heavy work such as parsing a large file, image processing or crypto, so the main thread stays responsive. The cost is copying data across and more complex code, so first check whether the work could be done on the server or paginated.
DOMContentLoaded fires when the HTML is fully parsed and deferred and module scripts have run, without waiting for images, iframes or late stylesheets. load fires only when every subresource, including images, has finished. Most app code only needs the DOM, so it should run at DOMContentLoaded (or simply as a defer/type="module" script): users can interact sooner, which helps perceived performance and INP. Waiting for load holds interactivity hostage to the slowest image. Use load only for code that genuinely needs final image sizes or every resource, such as measuring layout.
Last updated 23 Nov 2026.