Overview
Curated: · Written: · Reviewed:
DOM and browser rendering
A rendering question is a cost question in a different form. "Why does this animation stutter?", "why does the page flash unstyled for 300 ms?", "why did adding a resize listener make scrolling worse?" Each one is answered by naming the pipeline stage your change forces work into, and knowing what that stage costs. Interviewers use the pipeline as a probe. Anyone can recite "DOM, CSSOM, render tree, layout, paint" from a blog post. Far fewer candidates can say which CSS properties skip layout, why reading offsetHeight inside a loop is a bug, or what exactly blocks the first paint.
The mental model: an HTML document becomes pixels through a fixed pipeline (parse, style, layout, paint, composite), and every DOM or CSS change re-enters that pipeline at the earliest stage it affects. Rendering performance means pushing changes to later stages, or shrinking the part of the tree they touch.
Two properties decide most of these answers. The first is correctness: does the markup say what it means, to the browser and to assistive technology. The second is cost: how many pipeline stages does a given change wake up. Keep both in view and the follow-up questions mostly answer themselves.
Bytes to pixels: the critical rendering path end to end
The browser takes these steps in order and does not skip ahead:
- Fetch. HTML arrives as bytes and is decoded to characters, using the charset from the response headers or a
<meta charset>. - Parse HTML to DOM. The tokenizer emits tags and text. The tree builder turns them into nodes under
document. - Parse CSS to CSSOM. Stylesheets become a style sheet object with parsed rules. A stylesheet that applies to the current media environment is render-blocking: the browser will not paint until it has the CSSOM.
- Style. The browser matches each element against the rules, resolves the cascade, specificity, inheritance and custom properties, and attaches computed styles.
- Layout (reflow). Every box gets a size and a position in CSS pixels relative to the viewport.
- Paint. Boxes become an ordered list of drawing operations (display lists): fill this rect, draw this text, blit this image, cast this shadow.
- Composite. Painted content is rasterized into layer textures, uploaded, and assembled by the GPU into the frame that reaches the screen.
Step 3 blocks painting because early browsers rendered with a guessed stylesheet and repainted once the real one arrived. That produced the flash of unstyled content they were known for. The spec makes the CSSOM a precondition for the first paint to prevent it.
Parsing is incremental. The browser can lay out and paint partial content before </html> arrives, so first contentful paint can happen while the rest of the body is still downloading. That only holds if the parser is not waiting on a render-blocking stylesheet or a parser-blocking script. The critical rendering path is the set of resources that must arrive before that first pixel: the HTML, any render-blocking CSS, and any web font the first-paint text depends on. Without font-display, Chrome keeps text invisible for up to 3 s while it waits for a font, then swaps.
The standard advice follows from this. Inline the CSS the first screen needs, load the rest without blocking, and keep the initial HTML small enough that the parser reaches first paint quickly.
Parsing HTML, CSS and JavaScript: what blocks what
The HTML parser is a state machine (the spec calls its states insertion modes), and it is forgiving by design. An unclosed <div> or a stray </p> is corrected rather than rejected, which is why malformed pages still render. For performance, what matters is that the parser can be stopped, and what stops it.
Scripts. A classic <script src> or inline <script> halts HTML parsing while the browser fetches and runs it. Nothing after it is parsed, so nothing after it reaches the screen. Three attributes change this:
defer: the fetch runs in parallel with parsing. Execution happens after the document is parsed, in document order, beforeDOMContentLoaded.async: the fetch runs in parallel and execution happens as soon as the script is ready. Order is not guaranteed.type='module': deferred by default. Addasyncto get the unordered behaviour back.
The speculative preload scanner is why a blocking script does not necessarily delay the network. While the main parser is stuck on a script, a lightweight scanner keeps reading ahead and starts fetches for images, stylesheets and later scripts. A blocking script reliably delays parsing and first paint. The resources below it are often already in flight when it finishes.
Stylesheets. A <link rel='stylesheet'> whose media query matches blocks rendering. One that does not match (media='print', or a query that is false for the current viewport) is fetched at low priority and blocks nothing. Less widely known: CSS also blocks script execution. A classic script placed after a stylesheet will not run until that stylesheet's CSSOM exists, because the script may read computed styles. A slow <link> in <head> therefore delays the page twice: once for paint, and again for every inline script that follows it.
<!-- Parser blocked here: nothing below renders until app.js is fetched and run -->
<script src='/app.js'></script>
<!-- Preferred when order matters and the script touches the DOM -->
<script src='/app.js' defer></script>
<!-- Preferred for independent scripts such as analytics or a polyfill loader -->
<script src='/analytics.js' async></script>
Two events bracket all of this. DOMContentLoaded fires once the DOM is parsed and all deferred scripts have run. load waits for every subresource. A document.write() called after the document has finished loading implicitly calls document.open(), which discards the document and starts over. That is a live bug, not a historical curiosity.
What interviewers probe. Suppose someone says: "The page shows nothing for 400 ms and there is one script in <head>. What is happening?" A weak answer stops at "the script is blocking" and "move it to the bottom". A strong answer separates parse-blocking from render-blocking. It notes that a stylesheet above the script also delays that script's execution. Then it chooses defer or async based on whether order matters and whether the script reads the DOM.
DOM, CSSOM and the render tree
The DOM is nodes and attributes. It includes things that never appear on screen: <head>, <meta>, <script>, and every subtree under display: none. The render tree is the smaller tree of boxes that will actually be laid out and painted. It holds roughly one box per displayed element, plus anonymous boxes for text runs and generated boxes for ::before and ::after. (DevTools labels this tree differently across versions, so check the current name before quoting it.)
This distinction answers a pair of questions candidates often mix up:
display: none: no box is generated. The node stays in the DOM and its children still exist, but nothing in the subtree takes space or paints.getBoundingClientRect()on it returns zeros.visibility: hidden: the box is generated and laid out, so it keeps its space. It simply paints nothing.
The CSSOM is the parsed set of rules. During style recalc, the engine matches elements against those rules, and it does so right to left. For #app .card a, the engine finds every a and walks up its ancestors checking for .card and #app. It does not walk down from #app. So the rightmost simple selector determines the cost. A broad rightmost part such as .card * forces the engine to test many elements. A specific one such as a.nav-link does not.
The DOM is not the accessibility tree, and the render tree is not the accessibility tree either. See the semantics section below.
Style, layout, paint, composite: what each stage costs
| Stage | Work | Cost scales with |
|---|---|---|
| Style recalc | match rules, cascade, inherit | invalidated nodes times candidate rules |
| Layout | geometry for every box | size of the dirty subtree; flex and grid cost more than block flow |
| Paint | display-list operations | painted area times effect complexity (shadows, radii, filters, images) |
| Composite | raster and GPU assembly | layer count, layer area, changed region |
Style scales with the nodes invalidated, not with the whole document. Chromium maintains invalidation sets, so toggling a class on a leaf re-styles that element and whatever it affects. The exception is inherited properties. Changing font-size or color on a common ancestor recomputes the whole subtree.
Layout is the expensive stage on large trees because it is recursive. A height change on an element in normal flow invalidates its following siblings and its parent, and the dirty set can widen as layout proceeds.
Paint records drawing operations per layer. Expensive effects cost more per pixel: a box-shadow or border-radius over a large element costs more than a flat background of the same size.
Composite is cheap per frame but memory-hungry. A promoted layer of 1000 by 1000 CSS pixels on a 2x device pixel ratio screen rasterizes at 2000 by 2000 device pixels. At 4 bytes per pixel that texture is about 16 MB of GPU memory. Ten such layers come to roughly 160 MB, which is a real budget on a mid-range phone.
The frame budget ties these together. At 60 Hz you have 16.7 ms per frame for JavaScript, style, layout and paint combined. At 120 Hz you have 8.3 ms. Any long task inside that window drops a frame.
Reflow, repaint and compositing: choosing cheap changes
Every change re-enters the pipeline at the earliest stage that depends on it:
| Change | Style | Layout | Paint | Composite |
|---|---|---|---|---|
transform: translateX() on a composited layer | no | no | no | yes |
opacity on a composited layer | no | no | no | yes |
background-color, color | yes | no | yes | yes |
visibility: hidden | yes | no | yes | yes |
width, top, margin, font-size, node insert or remove | yes | yes | yes | yes |
Rows in the last group cause a reflow. Changes that only affect pixels cause a repaint. Animating top or left reflows and repaints on every frame. Animating transform on a composited layer does neither. This is why the transform and opacity rule of thumb exists.
Forced synchronous layout is the trap interviewers test most often, because it turns an innocent-looking loop into one that is quadratic in cost. The browser normally batches style and layout until the end of the task. Reading a geometry property forces that pending work to flush immediately. A read-after-write loop therefore triggers a full layout on every iteration.
// Anti-pattern: each iteration writes, then reads, forcing a synchronous layout
for (const el of document.querySelectorAll('.row')) {
el.style.width = el.offsetWidth * 2 + 'px';
}
Properties that force the flush include offsetWidth, offsetHeight, offsetTop, clientWidth, scrollTop, getBoundingClientRect() and getComputedStyle(el).width.
// Fixed: read everything first, then write everything, so layout runs once
const rows = Array.from(document.querySelectorAll('.row'));
const widths = rows.map((el) => el.offsetWidth);
rows.forEach((el, i) => { el.style.width = widths[i] * 2 + 'px'; });
The cost depends on the page, so measure your own. A Performance trace on a document of a few thousand nodes shows whether each forced layout is visible as a block on the main thread. A loop that forces layout a hundred times against a large list can easily consume a noticeable slice of a frame budget. A single batched pass does the same work once.
The rest of the toolkit, roughly in order of preference:
- Batch reads and writes, or schedule writes in
requestAnimationFrame. - Prefer
transformandopacityfor animation. contain: layout paintlimits a subtree's influence so that a change inside it cannot dirty its ancestors.content-visibility: autoskips rendering work for off-screen subtrees until they approach the viewport.will-change: transformallocates a layer before the animation starts. The memory is paid whether or not the animation runs, and applying it broadly lowers frame rate.
Event propagation: capture, target, bubble
Dispatching an event builds a propagation path from window down to the target and back up. Listeners fire in three phases:
- Capture. Ancestors from
windowtoward the target. Only listeners registered with{ capture: true }run here. - Target. Listeners on the element itself.
- Bubble. Ancestors from the target back out to
window, for listeners on events that bubble.
<div id='outer'><button id='inner'>click</button></div>
<script>
const log = [];
const outer = document.getElementById('outer');
const inner = document.getElementById('inner');
outer.addEventListener('click', () => log.push('outer capture'), true);
inner.addEventListener('click', () => log.push('inner capture'), true);
inner.addEventListener('click', () => log.push('inner bubble'));
outer.addEventListener('click', () => log.push('outer bubble'));
inner.click();
console.log(log.join(' -> '));
// outer capture -> inner capture -> inner bubble -> outer bubble
</script>
addEventListener(type, handler, options) accepts capture, once, passive and signal. Inside a handler, event.target is where the event originated, and event.currentTarget is the element whose listener is running. Confusing the two is what breaks delegated handlers.
stopPropagation() stops the event from travelling further along the path, but other listeners on the same element still run. stopImmediatePropagation() stops those too. preventDefault() works on a separate axis. It cancels the default action and has no effect on propagation.
Which events bubble determines what delegation can catch. focus and blur do not bubble, so use focusin and focusout instead. mouseenter and mouseleave do not bubble either, so use mouseover and mouseout. load does not bubble. A delegated handler on a common ancestor never sees these unless it registers in the capture phase.
// Delegation: one listener covers an unbounded list of items
list.addEventListener('click', (e) => {
const item = e.target.closest('.item');
if (!item || !list.contains(item)) return;
select(item.dataset.id);
});
passive: true promises that the handler will not call preventDefault(), which lets the compositor scroll or zoom without waiting for the main thread. Chrome treats touchstart, touchmove and wheel listeners on the root targets as passive by default. A non-passive wheel handler on a scrolling container is still a common, avoidable cause of scroll jank.
Semantic HTML and the accessibility tree
The browser builds a third tree from the DOM: the accessibility tree. It filters out presentational nodes and gives each remaining node a role, an accessible name, states and properties. Assistive technology reads this tree, not the raw markup.
Native elements supply the role and the behaviour together:
<!-- Role: generic. Not focusable, no activation, no name. -->
<div class='btn' onclick='save()'>Save</div>
<!-- Role: button. Focusable, Enter and Space activate it, name is Save. -->
<button type='button' onclick='save()'>Save</button>
That is why <div onclick> is a bug and not a style choice. Keyboard users cannot reach it, and screen readers do not announce it. <nav>, <main>, <header>, <h1> to <h6>, <table>, <label for>, <details> with <summary>, and <dialog> each map to a role and to browser behaviour you would otherwise rebuild in JavaScript, with more code on the main thread.
Name computation has its own rules. A <button> takes its accessible name from its text content. A form control takes its name from its associated <label>. A placeholder does not count as a name. A <div role='img' aria-label='Revenue by quarter'> is announced. An <img> with no alt attribute is not.
Two follow-ups separate strong candidates. First: is the DOM the accessibility tree? No. The accessibility tree is derived from the DOM, filtered, and augmented by ARIA. Second: why does heading order matter? Screen reader users skim pages by heading, so jumping from h1 straight to h4 misrepresents the page's structure.
Measuring rendering performance and reading the traces
In Chrome DevTools' Performance panel, record an interaction and read the main-thread track. Tasks appear as blocks, and expanding them shows Recalculate Style, Layout, Update Layer Tree and Paint. A warning on a task, such as a forced reflow violation, points to the read-after-write loop directly.
From JavaScript, PerformanceObserver reports the same signals in production:
const obs = new PerformanceObserver((list) => {
for (const e of list.getEntries()) {
console.log(e.entryType, e.startTime.toFixed(1), e.duration.toFixed(1));
}
});
obs.observe({ type: 'longtask', buffered: true });
// main-thread tasks over 50 ms
obs.observe({ type: 'layout-shift', buffered: true });
// CLS contributions
obs.observe({ type: 'largest-contentful-paint', buffered: true });
// LCP candidates
obs.observe({ type: 'event', buffered: true, durationThreshold: 40 });
// INP attribution
Lab and field data answer different questions. Lighthouse runs a throttled, simulated load on one machine. It is useful for catching regressions and says little about your real users. Field data from CrUX, or from the web-vitals library reporting from real sessions, is what gets scored. The Core Web Vitals thresholds, judged at the 75th percentile, are:
- LCP: 2.5 s or less is good, above 4.0 s is poor.
- INP: 200 ms or less is good, above 500 ms is poor.
- CLS: 0.1 or less is good, above 0.25 is poor.
FID was retired in March 2024 and replaced by INP.
When asked to prove which stage is at fault, give a sequence of steps, not an opinion. Record a trace of the interaction with CPU throttling enabled. Find the long tasks, and check whether Layout sits inside them. Then change the animated property to a composited one and record again. If the Layout blocks disappear, you have shown the cause.
Failure modes, misconceptions, and when not to optimise
These are the claims that most often go wrong in an interview:
- Stylesheets do not block rendering. A matching stylesheet does block rendering, and it also blocks execution of classic scripts that follow it.
display: noneis free. It generates no boxes, so there is no layout or paint for the subtree. The nodes are still parsed, still in the DOM, and still matched by style rules.- Reading
offsetWidthis free. It flushes pending style and layout. Inside a loop, that read is the cost. transformanimations are free. They are cheap only when the element sits on a composited layer that is not repainting. Each promoted layer costs GPU memory, about 16 MB for a 1000 by 1000 CSS pixel layer at 2x DPR.visibility: hiddenremoves the element. It keeps its space and only stops painting.- Event delegation catches everything. It misses
focus,blur,mouseenter,mouseleaveand other non-bubbling events, unless you register in the capture phase. will-changealways helps. It allocates a layer up front, and applied broadly it reduces frame rate.
On when not to optimise: measure first. A single layout over five nodes takes microseconds and does not justify a code change. Most slow pages are slow because of the network and the JavaScript bundle, not layout. Adding will-change or rewriting markup before reading a trace tends to make numbers worse. Optimise the stage the trace names, in the subtree the trace names, and leave everything else alone.
A weak answer lists the pipeline stages correctly but never says which stage a given change forces. It recommends a fix for performance without naming the resource or the measurement that would show the fix helped.