Skip to content
Tech Interview Prep
Technical interview guideNew

DOM and Browser Rendering

How the browser turns HTML, CSS and JavaScript into pixels: the critical rendering path, style/layout/paint/composite, what reflow and repaint actually cost, event propagation, and semantic HTML. These decide both whether a page is correct and how fast it feels.

Read
16 min
Practice MCQs
25
Interview Q&A
25
Edition
v1
Editorial status
Reviewed
Relevant for
Frontend Engineer

Scope: Current to the WHATWG HTML Living Standard and the CSSOM/Event specs; rendering-pipeline behaviour described is Chromium's as documented on web.dev and chromium.org, with Gecko and WebKit differences called out where they change the answer. Checked against Chrome 131, Firefox 133, Safari 18..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-4

Walk me through the DOM, the CSSOM and the render tree, and tell me what ends up in the render tree that has no DOM node, and what has a DOM node but never reaches it.

Answer

The 90-second answer. Three trees, built in order, each answering a different question. The DOM is the parsed document: every element, text node and comment, including the ones that will never be drawn. The CSSOM is the parsed and cascade-resolved style data: rules from <style>, <link> and style attributes, matched against selectors and resolved to a computed style per element. The render tree is the join of the two, holding one box per thing that gets laid out and painted, each box carrying its computed style. Blink calls it the layout tree, WebKit calls it the render tree; in neither engine is it the DOM with styles stapled on. It is a filtered join, and the filter runs in both directions.

The filter is display. Computed display: none generates no box, and neither do the descendants, so the subtree stays in the DOM and is absent from the render tree. visibility: hidden is the other case: the box is generated, occupies space, and is not painted.

DOMRender tree
<p>Hello</p>block box + inline text box
<p style="display:none"> and its subtreenothing
<p style="visibility:hidden">box, laid out, not painted
.badge::before { content: "new" }inline box, no DOM node behind it
<head>, <script>, <style>, <link>, <template>nothing
comment nodenothing
<input type="range">UA shadow tree boxes (Chromium)
<div style="display:contents">no box; children get boxes

The rows above the line are the ones people forget. Pseudo-elements are the cleanest render-tree-only content: ::before and ::after create real boxes with real text, and no node exists for them anywhere in the document. Anonymous boxes are the second: a block container with mixed inline and block children gets an anonymous block box wrapping the inline run, because the box tree has to be well-formed even when the markup isn't. Third, form controls and <video controls> render from a user-agent shadow tree in Chromium: boxes whose nodes are not in the page's DOM at all.

const hidden = document.querySelector('.hidden');   // <p class="hidden">A</p>
hidden.offsetWidth;                        // 0 — no box was ever laid out
getComputedStyle(hidden).display;          // "none" — the CSSOM resolved it anyway
getComputedStyle(hidden).width;            // "auto" — computed value, not a used one
document.querySelector('.badge').textContent;  // "C" — the ::before text is not here

That snippet is the practical consequence: style resolution and layout are separate stages, so a display: none element has a full computed style and no geometry. getComputedStyle answers from the CSSOM; offsetWidth, getBoundingClientRect and IntersectionObserver answer from layout and return zeros.

Failure modes. Measuring a hidden element to decide a layout, the classic tab-panel or tooltip measurement, returns 0 and the code silently positions at the origin; detect it by asserting non-zero geometry in a test, or measure after making the element visible but off-screen (position: absolute; visibility: hidden keeps the box). Generated content carrying meaning: ::before text is invisible to textContent, to querySelector and to most test queries, so a badge count or required-field marker built that way is untestable and fragile for assistive tech. Put real text in a real node. display: contents on a wrapper removes its box, which is what you want for a flex pass-through and is a trap when the element also carried a background, border or role. And content-visibility: auto skips rendering for off-screen subtrees, so their children report zero geometry until they come near the viewport.

If pushed on ordering: the render tree for a given piece of content can't be built until the CSSOM is complete, which is why a stylesheet in <head> is render-blocking, and why a script that reads layout forces style and layout to be flushed synchronously.

Curated: · Written: · Reviewed:

Q&A-1

Walk me through the critical rendering path for a simple page, from HTML response to first painted frame: name each stage and what can block it.

Answer

The 90-second answer. Six stages, in order: response → DOM, CSS → CSSOM, DOM + CSSOM → render tree, render tree → layout, layout → paint, paint → composite. Two of them can be blocked by the page's own markup: a stylesheet in <head> blocks rendering, and a classic <script> blocks the parser. Everything else (images, iframes, fonts) is off the critical path for the first frame, with the caveat that a webfont can hold text back for up to 3 seconds.

StageInOutBlocked by
FetchrequestHTML bytesDNS, TCP, TLS, TTFB
ParseHTML bytesDOMclassic <script> without defer/async
StyleCSS bytesCSSOMevery render-blocking stylesheet
Render treeDOM + CSSOMrender treeboth of the above finishing
Layoutrender treebox geometryviewport size, font metrics
Paint + compositegeometrypixelsmain-thread long tasks

The render tree is not the DOM. It holds only nodes that generate boxes: display: none subtrees, <head>, <script> and <meta> are dropped; visibility: hidden and ::before/::after content are kept.

A worked trace. Illustrative, 4G at 60 ms RTT, 14 KB of HTML, one 30 KB stylesheet, one deferred script:

  • 0 ms: navigation starts; DNS + TCP + TLS 1.3 costs ~2 RTT before the request is even sent.
  • ~180 ms: first byte of HTML.
  • ~200 ms: HTML fully received; the preload scanner has already fired the CSS request from the <head>.
  • ~290 ms: CSSOM complete.
  • ~300 ms: DOM complete (the deferred script runs after this).
  • ~315 ms: render tree built, layout done.
  • ~330 ms: first paint.

The gap between 200 and 290 ms is the whole lesson: the browser had the DOM at 300 ms but could not paint at 200 ms, because paint needs the CSSOM.

Why each blocker blocks. CSS is render-blocking because the browser refuses to paint a frame it would have to redo: a stylesheet arriving after first paint means a visible flash of unstyled content. A stylesheet with a non-matching media (say media="print") is fetched at low priority but does not block.

A classic <script> halts the HTML parser at the tag, so nothing below it is even discovered. If a stylesheet precedes it, the script also waits for the CSSOM, because it might call getComputedStyle. defer downloads in parallel and runs after parsing, in document order, before DOMContentLoaded; async runs as soon as it downloads, order not guaranteed.

<head>
  <link rel="stylesheet" href="critical.css">            <!-- render-blocking, intended -->
  <link rel="stylesheet" href="print.css" media="print">  <!-- fetched, not blocking -->
  <link rel="preload" as="style" href="late.css" onload="this.rel='stylesheet'">
  <script src="analytics.js" async></script>              <!-- parser keeps going -->
  <script src="app.js" defer></script>                    <!-- after parse, in order -->
</head>

Failure modes.

  1. Late-discovered CSS. @import inside a stylesheet, or a stylesheet injected by a script, is invisible to the preload scanner, so the CSS request starts a full round trip after the HTML. Detect: the DevTools Network waterfall shows the CSS request starting after the script that injected it; Lighthouse's critical request chain shows the extra depth.
  2. Synchronous script above the fold. A blocking <script> in <head> before any content means a blank screen for download + parse + execute. Detect: the Performance panel shows a long Parse HTML gap, and FCP tracks the script's finish rather than the HTML's.
  3. Font block period. font-display: auto (the default) hides text for up to 3 s while the font loads, then swaps. Detect: FCP moves but the filmstrip shows no text; document.fonts.status stays loading.
  4. Missing image dimensions. Not a paint blocker, but layout runs again when the image arrives: that is CLS, not FCP. Detect: Layout Shift entries in the Performance panel.

When not to optimise this. If TTFB dominates (server rendering, no CDN) inlining critical CSS buys nothing; the HTML itself is the bottleneck. Measure first: PerformanceObserver on paint gives FP and FCP, and the gap between them and domContentLoaded tells you whether you are blocked on CSS, on scripts, or on the network.

Curated: · Written: · Reviewed:

Q&A-14

Walk me through how the HTML parser recovers from mis-nested tags, why <table> parsing uses foster parenting, and why the resulting DOM can differ from the source you wrote.

Answer

The 90-second answer. The HTML parser is not a validator; it is a recovery algorithm specified in the HTML Standard. It builds the DOM by maintaining a stack of open elements and a current insertion mode. When it sees a tag that doesn't fit the mode, it applies rules: it may auto-close open elements, ignore the tag, or reparent nodes. Mis-nested formatting tags like <b><i></b></i> are handled by the adoption agency algorithm, which closes and reopens elements to produce a well-formed tree. Tables are special because their content must be structured; the parser has insertion modes like "in table" and "in table text". Content that appears inside a table but isn't allowed there (text, <div>, etc.) is foster-parented: moved to just before the table in the DOM. The DOM you get is the parser's output, so it can differ from your source. This matters for hydration, CSS selectors, and JS traversal.

Mechanism. The parser's stack of open elements tracks the current nesting. For <p>1<b>2<i>3</b>4</i>5</p>, the stack goes [html, body, p, b, i]. When it sees </b>, the adoption agency algorithm runs: it closes the <i>, closes the <b>, and then reconstructs the <i> for the remaining content. The resulting DOM is <p>1<b>2<i>3</i></b><i>4</i>5</p>. You can verify this in any browser:

const html = '<p>1<b>2<i>3</b>4</i>5</p>';
const doc = new DOMParser().parseFromString(html, 'text/html');
console.log(doc.body.innerHTML);
// <p>1<b>2<i>3</i></b><i>4</i>5</p>

For tables, the parser enters "in table" mode after <table>. A <div> start tag is not allowed, so it triggers foster parenting: the <div> is inserted before the <table> in the DOM. The same happens to text.

const html = '<table><div>hello</div></table>';
const doc = new DOMParser().parseFromString(html, 'text/html');
console.log(doc.body.innerHTML);
// <div>hello</div><table></table>

Here's a table of common cases:

SourceDOM (body.innerHTML)
<p>1<b>2<i>3</b>4</i>5</p><p>1<b>2<i>3</i></b><i>4</i>5</p>
<table>text</table>text<table></table>
<table><div>hello</div></table><div>hello</div><table></table>
<ul><li>a<li>b</ul><ul><li>a</li><li>b</li></ul>

Failure modes. 1. Hydration mismatch. If your server renders HTML that the parser normalizes differently than your client-side virtual DOM expects, React (or similar) will warn and may discard the server-rendered DOM. Detect: React hydration warnings in the console, or compare document.body.innerHTML with the server output. 2. CSS selectors that assume source structure. table > div returns null because the div was foster-parented. Detect: query in the console. 3. innerHTML round-tripping. Setting element.innerHTML = '<table>text</table>' and reading it back gives text<table></table>. Detect: compare before and after.

When not to worry. If you always emit valid HTML, the parser's recovery rarely changes the tree. But you can't assume your templating engine, CMS, or users do. The parser is designed to be forgiving, and the DOM is the source of truth for rendering, not your source file.

Curated: · Written: · Reviewed:

Q&A-2

Why does a synchronous <script> in <head> block rendering, and what exactly do defer and async change about parsing, execution order and DOMContentLoaded?

Answer

The 90-second answer. The HTML parser builds the DOM incrementally on the main thread, and that same thread runs style, layout and paint. A classic <script src> with neither defer nor async is a hard stop: the parser halts at the tag, fetches the script if it isn't cached, executes it, then resumes. Nothing below the tag exists in the DOM while it runs, and nothing paints. defer and async both take the download off the critical path, the parser keeps going while the file arrives, and differ in when execution happens and what it is ordered against.

  • defer: executes after the document is parsed, in document order, before DOMContentLoaded fires.
  • async: executes the moment its download finishes, in whatever order downloads finish, possibly mid-parse. DOMContentLoaded does not wait for it; the load event does.
fetchexecutesorderblocks parsinggates DOMContentLoaded
classicblocks parserimmediatelydocumentyesyes
deferparallelafter parsedocumentnoyes
asyncparallelon arrivalarrivalyes, brieflyno

One rule that catches people: a script (blocking, deferred or async) cannot execute while a stylesheet is still loading, because it might read computed styles. A <link rel="stylesheet"> in head therefore delays every script behind it, which is why the critical rendering path is DOM + CSSOM → render tree → layout → paint.

Trace it. Hypothetical numbers, one page:

<head>
  <link rel="stylesheet" href="app.css">  <!-- 100 ms -->
  <script src="analytics.js"></script>    <!-- 150 ms fetch, 20 ms exec -->
</head>
<body>
  <h1>Hello</h1>
  <script src="app.js" defer></script>
</body>

Blocking: t=10 parser hits the link, CSS fetch starts; t=20 it hits the script and stops; t=170 the script runs to t=190; the parser resumes and the DOM completes at t=190. First paint needs DOM and CSSOM, so it lands at ~190 ms, and DOMContentLoaded with it.

With defer on analytics.js: fetch starts at t=20, parsing continues, DOM completes at t=30, CSSOM at t=110, so first paint is ~110 ms. 80 ms earlier. The script still runs at t=170 and DOMContentLoaded still waits for it, so that event stays at ~190 ms. defer buys paint, not DOMContentLoaded.

With async: first paint still ~110 ms, but DOMContentLoaded fires at ~30 ms, before the script has run. Any handler that assumes the analytics global exists is now racing.

Failure modes.

  1. Async scripts with a dependency. Two async bundles execute in arrival order, so B can run before A on a slow network and only there. Detect by throttling to Slow 3G and reading performance.getEntriesByType('resource') order. Fix: defer, or type="module" (deferred by default), or a dynamic import().
  2. Inline scripts ignore both attributes. <script defer>window.__cfg = {}</script> runs at parse time, immediately. A config block placed after a deferred bundle still executes first: usually what you want, occasionally a surprise.
  3. A slow third-party defer script delays every DOMContentLoaded handler, including framework bootstrap. Analytics belongs in async; app code that needs the DOM belongs in defer.
  4. document.write from a deferred or async script is ignored with a console warning, so a legacy loader silently does nothing.

When not to use them. A tiny inline bootstrap that must run before first paint, a theme class on <html> to avoid a flash, has no src, so defer is meaningless; keep it inline and small. And nothing here helps if the script is on the critical path by necessity: a blocking script that must run before the body renders is a design smell, not a tuning problem.

Curated: · Written: · Reviewed:

Q&A-3

Walk me through how the browser decides which stylesheets block the first paint, and what `media`, `preload` and inlining each change about that decision.

Answer

The 90-second answer. The render tree is the DOM plus the CSSOM, and the browser won't paint a node until it knows that node's computed style. So every <link rel="stylesheet"> the parser meets is a render-blocking resource: first paint waits for the CSS to download and parse. The media attribute is the one lever the browser gives you for free, if the query doesn't match the current environment, the sheet isn't needed to paint and stops blocking. preload doesn't change blocking at all; it only starts the fetch earlier. Inlining critical CSS removes the round trip, and the round trip is the only thing that actually costs you.

Mechanism. Two consequences people miss. First, stylesheets block scripts as well as paint: a <script> after a pending stylesheet waits for it, because the script may call getComputedStyle. Second, @import inside a stylesheet serializes: the browser can't discover the imported file until it has parsed the parent, so each @import adds a full RTT to the critical path.

media. media="print" on a screen, or media="(min-width: 60em)" on a 500px viewport, doesn't match, so the sheet isn't render-blocking. Chrome still fetches it at low priority so it's ready if the environment changes. The catch: if the query starts matching later (a resize, a print) the sheet applies then and triggers a re-style. That's the standard async-CSS pattern:

<link rel="stylesheet" href="non-critical.css" media="print" onload="this.media='all'">
<noscript><link rel="stylesheet" href="non-critical.css"></noscript>

media="print" never matches on screen, so the fetch doesn't block; onload flips it to all once it's cached, and the rules apply with no extra request.

preload. <link rel="preload" as="style"> puts the fetch on the preload scanner's high-priority queue, so it starts before the parser would have found it: useful for a sheet referenced from inside another CSS file, or one injected by JS. It does not make the sheet non-blocking. Pair it with the flip:

<link rel="preload" as="style" href="app.css" onload="this.rel='stylesheet'">

Inlining. A <style> block has no request, so the CSSOM is ready when the parser reaches the end of it. That's critical CSS: inline the above-the-fold rules, load the rest async. The cost is that inlined CSS isn't cached across navigations and is duplicated in every HTML response.

Worked trace. Server 100 ms away, HTML 20 KB, main.css 30 KB.

ApproachFirst paint
Blocking <link>100 ms HTML RTT + 100 ms CSS RTT ≈ 200 ms
@import inside that CSS≈ 300 ms
Inlined critical CSS≈ 100 ms

The gap is one RTT, not the 30 KB.

Failure modes.

  1. FOUC from the async flip. If onload runs after first paint, the page paints unstyled then restyles. Detect: the WebPageTest filmstrip shows a flash, or a layout-shift PerformanceObserver shows a CLS spike.
  2. Non-matching media that later matches. A (min-width: 60em) sheet isn't blocking at 500px, but resizing to 1000px applies it and forces a re-layout. Detect: resize with the Performance panel open and watch for a style recalculation.
  3. Stylesheet delaying a script. An inline <script> after a slow sheet is delayed. Detect: the Performance panel shows Evaluate Script starting after Parse Stylesheet.

When not to. If the CSS is small and already cached, a plain blocking link is simpler and avoids the FOUC risk. Inline only what the first viewport needs; inlining the whole sheet trades a cacheable request for uncacheable bytes on every navigation.

Curated: · Written: · Reviewed:

Q&A-15

Walk me through what document.write does to the parser and the critical path, why it's worse on a slow connection than a plain blocking script, and what you'd use instead.

Answer

The 90-second answer. document.write() is a parser operation, not a DOM one. While the HTML parser is running, it inserts the string into the parser's input stream at the insertion point, the position of the script that called it, and the parser tokenizes it in whatever insertion mode it is currently in. It is not a fragment parse like innerHTML. Once parsing has finished there is no insertion point, so document.write() falls back to document.open(), which replaces the whole document.

The critical-path cost: a <script src> written this way is parser-inserted, so it blocks the parser exactly like an inline blocking script, and its URL does not exist until the writing script has executed. The preload scanner only scans the raw HTML bytes; it never sees the token stream, so it cannot start the fetch early. Every hop is a serial round trip with the parser stopped.

What that costs. Illustrative numbers, 400 ms RTT, a <head> inline script that writes one third-party script which writes another:

t=0     HTML response starts, parser begins
t=120   parser reaches the inline <script>; blocks
t=125   inline script runs: document.write('<script src="https://ads.example/a.js">')
t=125   parser resumes, immediately hits the written script; blocks again
        the preload scanner never saw this URL — the fetch starts now
t=525   a.js arrives (1 RTT), runs, document.writes b.js
t=925   b.js arrives (1 RTT), runs
t=930   parser resumes; <body> is finally parsed

800 ms of parser blocking before the first body byte, on a page whose HTML took 120 ms. Nothing below the script (images, CSS, other scripts) was discovered in that window. The same tag as <script async src> in the HTML is found by the preload scanner in the first bytes and never stops the parser.

The alternatives.

<!-- parser-blocking, invisible to the preload scanner -->
<script>document.write('<script src="/js/enhanced.js"><\/script>')</script>

<!-- in the byte stream, discovered early, parser never blocks -->
<script defer src="/js/app.js"></script>
// app.js — deferred, so the parser has already finished
if (CSS.supports('display', 'grid') && 'IntersectionObserver' in window) {
  import('/js/enhanced.js');   // dynamic import: async, no parser involvement
}
blocks parserpreload scanner sees itexecution order
<script src> in HTMLyesyesdocument order
document.write('<script src>')yesnodocument order
<script async src>noyesas they arrive
<script defer src>noyesdocument order, after parsing
createElement('script') + appendnon/aasync by default; insertion order if async = false

For markup, insertAdjacentHTML or append: they touch the DOM, not the parser. For third-party tags you cannot edit, inject them after load or from a deferred script.

Failure modes.

  1. document.write from a script that runs after parsing. A deferred script has no insertion point; Chrome refuses the async case outright with "Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened." Where it does not throw, the fallback is document.open() and the page blanks. Detect: empty body, that console error.
  2. Chained writes on slow connections. Detect in the Performance panel: one long parser-blocking task with nested script evaluation, and a network waterfall where each request only starts after the previous script finished.
  3. Chrome's intervention. Since Chrome 53 (2016), parser-blocking cross-origin scripts injected via document.write() are blocked on 2G connections, with a console warning on faster ones. The tag silently does not load for those users. Detect: the console warning naming the URL, and a missing global in field data.

Curated: · Written: · Reviewed:

Q&A-16

Walk me through how the preload scanner finds subresources ahead of the parser, and why a script injected by JavaScript doesn't get the same treatment?

Answer

The 90-second answer. The preload scanner is a second, deliberately dumb tokenizer that reads the same HTML bytes ahead of the tree-building parser. It builds no DOM, runs no script and applies no CSS; it recognizes a fixed set of tags and attributes that imply a fetch, and starts those fetches early. It exists because the main parser is single-threaded and stalls: on a synchronous <script src> it stops until the script is fetched and executed, and a pending stylesheet can stall a script behind it. Without the scanner, everything after the stall would be discovered only when the stall cleared. With it, an <img> at byte 40 KB starts downloading while the parser is still stuck at byte 2 KB. It also runs continuously when nothing is blocked, so discovery is decoupled from parsing.

What it recognizes. Chromium's HTMLPreloadScanner; other engines are similar in shape.

In the byte streamPreloadedWhy
<script src>, <link rel=stylesheet>, <link rel=preload>yestag plus attribute is enough; async/defer don't matter
<img src>/srcset, <source srcset>, <video poster>yes
@import and url() inside an inline <style>yesBlink runs a CSS preload scanner over the style text
url() inside an external stylesheetnoneeds the parsed CSSOM
anything a script createsnonot in the byte stream

Why an injected script gets nothing. The scanner is a pure function of bytes it has already received. It never executes anything, so it cannot know what a script will create, and by the time the script runs the scanner has long since moved past that offset. A script element with src starts its fetch when it is inserted into the document, so the request begins after the parent script's own fetch, parse and execution. Parallel fetches become a chain. (In Chromium, document.write during parsing is a different case, the written markup goes back into the parser's input stream, but the fetch still starts when the write happens, not with the document.)

Hypothetical figures: 40 ms RTT, 80 ms transfer per script, 30 ms execution.

Static markup
t=0     HTML arrives; scanner sees a.js and b.js in the first chunk
t=0     both fetches start
t=120   both arrive
t=150   a.js executed; parser resumes with b.js already in memory

a.js injects b.js
t=0     HTML arrives; scanner sees only a.js
t=120   a.js arrives
t=150   a.js executed, inserts <script src=b.js>; fetch starts now
t=270   b.js arrives
t=300   b.js executed

150 ms versus 300 ms, from nothing but where the tag lives.

What to do instead. Put the tag in the HTML the server sends. If the resource is only known at runtime, emit <link rel="preload" as="script">, or rel="modulepreload" for a module graph, in the initial HTML, so the fetch starts with the document rather than with the script. Add fetchpriority="high" on the real tag if it competes with images for bandwidth.

Failure modes, and how you catch each.

  1. Waterfall chains. A loads B loads C, each waiting on the last. Detect: Network panel, the Initiator column reads the injecting script instead of "Parser", and the requests are stair-stepped rather than overlapping. In Resource Timing the entry's initiatorType is "script" rather than "parser".
  2. CSS-referenced assets. A hero background-image or a webfont is discovered only after the stylesheet is parsed, so it starts after the CSS response ends. Detect: waterfall ordering, initiatorType: "css".
  3. Wasted speculation. The scanner preloads an image a later script removes, or one that never renders. Detect: compare requests against what actually painted; on mobile the cost is real bytes.
  4. Nothing to scan yet. The scanner can only read bytes already received, so a server that buffers the whole document before flushing delays discovery of everything in it. Detect: TTFB against the start time of the first subresource request.

The scanner is a heuristic, not a guarantee, and it errs in both directions, which is why preload is worth reserving for resources on the critical path.

Curated: · Written: · Reviewed:

Q&A-5

Walk me through layout, paint and composite as three separate costs: what triggers each, what goes in and what comes out, and which is cheapest to repeat?

Answer

The 90-second answer. Once the render tree exists, producing a frame is a pipeline: style → layout → paint → composite. The three you asked about are strictly ordered, and each one's input is the previous one's output, so invalidating layout invalidates paint and composite too.

  • Layout: input: the render tree plus the viewport; output: one box per render object with a position and size in CSS pixels, relative to its containing block. Triggered by anything that changes geometry: inserting or removing nodes, text changes, width/height/margin/padding/border-width/font-size, a viewport resize, a web font swapping in.
  • Paint: input: those boxes plus paint order and visual styles; output: a display list of draw commands (fill rect, draw text, draw image) per layer, which raster threads turn into bitmaps. Triggered by visual changes that move nothing: color, background-color, border-color, visibility, box-shadow.
  • Composite: input: the layer tree, each layer carrying a transform, opacity and clip; output: the frame the GPU scans out. Triggered by transform/opacity changes on a layer that already exists, and by scrolling.

Cost ordering follows from where the work runs. Layout and paint are main-thread and scale with the number of affected boxes and the painted area. Compositing runs on the compositor thread and scales with the number of layers. So composite is the cheapest to repeat by a wide margin: that is the whole reason a transform animation holds 60fps while the main thread is busy parsing JSON, and a left animation does not.

ChangeStyle recalcLayoutPaintComposite
left: 0 → 500pxyesyesyesyes
background-coloryesnoyesyes
transform: translateX(500px) on a promoted layeryesnonoyes
scrollnononoyes

Trace: a 300×200 card sliding 500px over 500ms at 60Hz. 30 frames.

Animate left. Every frame: style recalc, layout of the card and any in-flow siblings whose position depends on it, paint of the card's area, composite. If layout is 4ms and paint 3ms, 7ms of a 16.7ms budget is gone before any of your JavaScript runs.

Animate transform: translateX(). The first frame pays the same work plus promotion: the card gets its own compositor layer and is rasterized once. The remaining 29 frames are a compositor-side matrix update: zero main-thread work. The bill arrives as GPU memory: 300×200 CSS px at DPR 2 is 600×400×4 bytes ≈ 0.96MB for that layer; a full-viewport 1920×1080 layer at DPR 2 is 3840×2160×4 ≈ 33MB.

Failure modes.

  1. Layout thrashing. Reading a layout property after writing one forces the browser to flush layout synchronously. for (...) { el.style.width = w + 'px'; total += el.offsetWidth; } runs a full layout per iteration. Detect: the Performance panel shows repeated Layout entries inside one task, and DevTools logs "Forced reflow while executing JavaScript".
  2. Layer explosion. will-change: transform on every row of a 500-row list creates 500 layers; compositing and GPU memory become the bottleneck. Detect: Rendering → Layer borders, or the Layers panel.
  3. Paint storms. Animating box-shadow or background-position repaints a large area every frame even though nothing moved. Detect: Performance panel paint rectangles, Paint time per frame.

When not to promote: a layer whose content or size changes every frame still repaints, so promotion buys nothing. Bound the scope instead (contain: layout paint on a widget, content-visibility: auto on off-screen sections) so a change stops invalidating the whole document.

Curated: · Written: · Reviewed:

Q&A-6

Which CSS properties can be animated without triggering layout or paint, and what makes that possible?

Answer

The 90-second answer. Three properties animate without layout or paint: transform, opacity, and, in Chrome, filter and backdrop-filter. Everything else falls into one of two buckets. Geometry properties (width, height, top, left, margin, padding, font-size, border-width) force layout, because the render tree's box positions have to be recomputed. Pixel-only properties (color, background-color, box-shadow, border-radius, visibility) force paint, because the pixels change but the boxes don't. Layout and paint both run on the main thread, so a long task or a React render stalls the animation mid-frame.

The mechanism is the compositor. When an element animates a compositor-only property, the browser promotes it to its own composited layer: the subtree is rasterized once into a GPU texture, and the compositor thread applies a new transform matrix or alpha value to that texture every frame. No style recalc, no layout, no paint, no main-thread work, which is why the animation keeps running at 60 fps while JavaScript blocks the main thread.

PropertyStyleLayoutPaintComposite
transform: translate/scale/rotate✓––✓
opacity✓––✓
filter: blur()/brightness()✓––✓ (Chrome)
top / left / width / height✓✓✓✓
background-color / box-shadow✓–✓✓

Style recalc happens in every row; the column that matters is what follows it.

/* main thread every frame: layout, then paint */
.panel { position: absolute; left: 0; transition: left 300ms; }
.panel.open { left: 240px; }

/* compositor only */
.panel { transition: transform 300ms; }
.panel.open { transform: translateX(240px); }

In a Performance recording, the first version shows Recalculate Style → Layout → Paint → Composite Layers inside every frame, and frames stretch to 30–40 ms whenever the main thread is busy. The second shows only Composite Layers, and the main-thread track is empty. The Layers panel shows the element as its own layer for the duration of the animation. A single, non-animated transform change still repaints: it's the animation path that promotes the layer.

Failure modes, and how you catch each.

  1. Layer memory. Each composited layer is a texture: a 1000×1000 element at 4 bytes/px is 4,000,000 bytes ≈ 3.8 MiB, and a full-screen 1920×1080 layer is ≈ 7.9 MiB. Promoting 50 list rows to animate them individually can exhaust VRAM on a mid-range Android and jank or kill the tab. Detect in the Layers panel; fix by animating one wrapper instead of every row.
  2. Blurry text under scale. The texture is rasterized at the element's layout size, so scaling to 4× magnifies existing pixels. Chrome re-rasters when the animation ends, so the blur is visible only during it. Detect by eye at the animation's midpoint.
  3. position: fixed descendants. A transformed ancestor becomes the containing block for fixed-position descendants, so a fixed header inside an animated container slides with it. Detect: the header moves in the trace when it shouldn't.
  4. will-change: transform left on permanently. It promotes the layer forever, paying the memory cost when nothing animates. Add it before the animation, remove it on transitionend.
  5. opacity on a huge subtree. Compositing a full-screen container with thousands of nodes costs a full-screen texture per frame; a small overlay is cheaper.

When not to use it. An accordion that must change height genuinely needs layout. Either accept main-thread layout when the main thread is idle, or use FLIP: measure the first and last positions, then animate transform from the inverted delta. scaleY() on the container is the wrong answer: it distorts the children.

Curated: · Written: · Reviewed:

Q&A-7

A 500-row list janks while scrolling. Walk me through how interleaved DOM reads and writes cause layout thrashing, how you'd confirm it in a profile, and how you'd restructure the code.

Answer

The 90-second answer. The browser batches rendering. Between tasks it runs style recalculation, layout and paint once, on a frame boundary: that batching is what makes DOM code cheap. It breaks when you ask for a layout-dependent value after you have already invalidated layout in the same task: the browser cannot answer from stale data, so it flushes style and layout synchronously, right there, before your next line runs. Do that in a loop and you get one forced layout per iteration. That is layout thrashing.

The rule: reads that need geometry (offsetWidth, offsetHeight, offsetTop, getBoundingClientRect(), scrollTop, getComputedStyle(el).width) force a flush when the tree is dirty. Writes that change geometry (style.width, classList.add, appendChild, textContent) dirty it. Reading el.style.width does not force anything; that is the inline declaration, not the computed box.

// 500 rows. Each iteration writes, then the next iteration reads → 500 layouts.
for (const row of rows) {
  row.style.width = row.offsetWidth + 10 + 'px';
}

// Reads first, writes second → 1 layout.
const widths = rows.map(r => r.offsetWidth);
rows.forEach((r, i) => { r.style.width = widths[i] + 10 + 'px'; });

Arithmetic: laying out a 500-row table is roughly 2–5 ms on a mid-range laptop (measure your own). 500 of them is 1–2.5 s of main-thread work; the batched version is one layout plus 500 cheap style writes. The frame budget is 16.7 ms at 60 Hz and 8.3 ms at 120 Hz, so ten forced layouts already blows it.

Confirming it in a profile. Record in Chrome DevTools Performance while scrolling. The signature is many Layout events stacked inside a single task, each followed by a few milliseconds of your own function, repeating. The Bottom-Up tab names it: "Forced reflow is a likely performance bottleneck". Firefox labels the same thing Sync reflow. A longtask PerformanceObserver entry over 50 ms tells you a frame blew the budget but not why: you need the trace to see the read/write alternation. Don't confuse this with layout shift (CLS): shift is geometry moving after paint, thrashing is geometry being recomputed repeatedly before paint.

Restructuring, in order of payoff:

  1. Batch. Collect every read into one pass, every write into another. FastDOM-style read/write queues do this mechanically across a codebase.
  2. Defer writes to requestAnimationFrame so they land before the next frame's layout instead of forcing one now. rAF alone does not fix thrashing: ordering does.
  3. Stop reading layout where you can. ResizeObserver and IntersectionObserver hand you sizes and positions after layout, with no forced flush. Cache a value you already read rather than re-reading it per iteration.

Shrink the layout scope too: contain: layout on the row container, or content-visibility: auto, keeps a write from invalidating the whole document. For animation, transform and opacity skip layout and paint entirely.

Failure modes. One getBoundingClientRect() in a scroll handler that also toggles a class is enough to thrash at 60 events/s. Libraries that measure inside a loop (carousels, virtual lists, tooltip positioning) are the usual culprits. Detect with the trace, not with performance.now() around the loop: timing tells you it is slow, the trace tells you which read forced it.

Curated: · Written: · Reviewed:

Q&A-20

Walk me through `content-visibility`, `contain` and `will-change`: what each one does to the rendering pipeline, what it buys you, and what it costs.

Answer

The 90-second answer. Three different levers at three different stages, and they get confused because all three are filed under "performance CSS".

contain is a promise of independence. contain: layout says nothing inside can affect layout outside, so a change in the subtree doesn't force the rest of the document to re-lay-out; it also makes the element a containing block for absolutely and fixed positioned descendants, and a stacking context. contain: paint says descendants can't paint outside the padding box, so the engine can skip painting offscreen descendants and treat the subtree as a paint boundary, and it clips. contain: size says the element's size doesn't depend on its contents, so the parent can lay out without laying out the children, and if you don't give it a size, it collapses to zero. contain: content is layout + paint + style; strict adds size.

content-visibility: auto is containment put to work. Offscreen subtrees are skipped entirely (no layout, no paint, no style recalc for their descendants) and rendered when they approach the viewport. That's the win on a 500-row list. hidden skips the contents but keeps the element's own box and lets the engine cache the subtree's rendering state, so toggling back is cheap; display: none throws the box tree away.

will-change is a compositor hint, not a layout one. It tells the engine a property is about to change so it can promote the element to its own layer ahead of time, which is what lets transform and opacity animations run on the compositor thread instead of the main thread. The cost is memory: a full-screen layer at 1920×1080 is 1920 × 1080 × 4 bytes ≈ 8.3 MB; on a 3× phone a full-screen layer is ~12 MB.

Stage it touchesBuys youCosts you
contain: layoutlayoutsubtree changes don't invalidate the rest of the documentnew containing block + stacking context
contain: paintpaintoffscreen descendants skipped; subtree is a paint boundaryclips overflow: tooltips, shadows, dropdowns
contain: sizelayoutparent lays out without the childrenelement sizes as if empty; zero height unless sized
content-visibility: autolayout + paintoffscreen subtrees not rendered at allcost moves to scroll; needs contain-intrinsic-size
will-change: transformcompositelayer promoted before the animation startsGPU memory per layer; stacking context + containing block
/* 500-row list, 64px rows */
.row {
  content-visibility: auto;
  contain-intrinsic-size: auto 64px; /* `auto` remembers the last rendered size */
}

Without contain-intrinsic-size the skipped rows have no height, so the scrollbar jumps and every scroll into new content is a layout shift. With it, the browser reserves 64px and, once a row has rendered, remembers its real size.

// will-change belongs around the change, not on the element forever
el.addEventListener('pointerenter', () => { el.style.willChange = 'transform'; });
el.addEventListener('transitionend', () => { el.style.willChange = 'auto'; });

Failure modes, and how you catch each.

  1. Clipping. contain: paint, and therefore content and strict, clips at the padding box. A dropdown or tooltip that overflows its container vanishes. Detect: it's in the DOM and in the accessibility tree but not on screen.
  2. Collapse. contain: size, or content-visibility without an intrinsic size, gives a zero-height element. Detect: scrollHeight changes as you scroll; CLS in the trace.
  3. Measurement returns zero. An element inside a skipped subtree has no box: getBoundingClientRect() is all zeros and offsetHeight is 0. Code that measures before the content renders gets garbage. Detect: log the rect and see 0.
  4. will-change changes layout semantics. will-change: transform creates a stacking context and a containing block for fixed-position descendants before any transform exists, so a position: fixed child that was pinned to the viewport is now pinned to the element. Detect: it moves.
  5. Layer explosion. will-change on every list item. Detect: DevTools → Layers, count layers, watch memory; on mobile the tab gets killed.
  6. Cost moved, not removed. content-visibility: auto renders each subtree as it enters the viewport, so a heavy row still janks: during scroll instead of at load. Detect: Performance trace during scroll shows Layout/Paint spikes.

One accessibility distinction worth stating: content-visibility: auto contents stay in the accessibility tree and are findable with Ctrl-F; hidden removes them. So hidden is not a drop-in for display: none on content that must stay reachable.

Curated: · Written: · Reviewed:

Q&A-8

Walk me through event propagation order for a click on a button nested three levels deep, which listeners fire, in what order, and why?

Answer

The 90-second answer. A dispatched event has a path: the target, then each ancestor up to window. Every node on that path is visited twice: once on the way down (capture) and once on the way up (bubble). addEventListener(type, fn, true) or {capture: true} registers for the downward pass; the default false registers for the upward pass. The target is visited in both passes: its capture listeners run first, then its bubble listeners, each group in registration order. That is the current DOM spec: changed in 2020, shipped in Chrome 89. Older engines ran both groups at the target in registration order, so code written before that can depend on the wrong order.

The trace. Three levels. Every node registers its bubble listener first:

<div id="outer"><div id="inner"><button id="btn">click</button></div></div>
// Chrome 126. btn.click() dispatches a real click: bubbles: true, composed: true
const path = [['window', window], ['document', document], ['html', document.documentElement],
              ['body', document.body], ['outer', outer], ['inner', inner], ['btn', btn]];
const log = [];
for (const [name, el] of path) {
  el.addEventListener('click', () => log.push(`bubble  ${name}`));       // registered first
  el.addEventListener('click', () => log.push(`capture ${name}`), true); // registered second
}
btn.click();
capture window
capture document
capture html
capture body
capture outer
capture inner
capture btn      <- target: the capture pass runs first
bubble  btn      <- then the bubble pass
bubble  inner
bubble  outer
bubble  body
bubble  html
bubble  document
bubble  window

Registration order is bubble-then-capture on every node, and capture still runs first on every node. The pass decides, not the registration order.

Mechanism. The spec's dispatch algorithm walks the path in reverse for the capturing pass and forward for the bubbling pass, calling inner invoke with that pass's phase. A listener is skipped when the pass phase and its capture flag disagree: the capturing pass skips non-capture listeners, the bubbling pass skips capture listeners. At the target event.eventPhase is AT_TARGET (2) in both passes, but the pass phase still governs the skip, which is why the target's capture listeners run in the capturing pass rather than in registration order.

Inside any listener, event.target is the node the event was dispatched at and never changes; event.currentTarget is the node whose listener is running, and is null after dispatch.

Delegation vs direct binding. One listener on a container, or one per element. Delegation wins when the set is large, dynamic, or unknown at bind time: rows added after mount need no rebinding, and teardown is one removeEventListener. Direct binding wins when the set is small and static, when the event does not bubble, when each element carries its own state, and when the handler must not run for unrelated descendants: a mousemove listener on document runs for every mousemove on the page, one bound to the canvas runs only there.

The costs are symmetric. Delegation pays a closest() per event (a few ancestor hops) and runs the handler for every descendant event, including ones you ignore. Direct binding pays N listeners, each retaining its closure: a 10,000-row table is 10,000 closures alive until the rows go, plus 10,000 addEventListener calls at mount.

Failure modes.

  1. A capture listener on document that calls stopPropagation(). The event never reaches the target, so every delegated handler on the page goes silent. Detect: getEventListeners(document) in the DevTools console, or an Event Listener Breakpoint on click that never fires at the target.
  2. Delegation reading event.target directly. The click lands on a <span> inside the button, event.target.matches('button') is false, and the handler does nothing. Use closest() and null-check the result.
  3. Delegating a non-bubbling event. focus, blur, mouseenter, mouseleave and load never bubble, so an ancestor listener never fires. Use focusin/focusout, or {capture: true}, which reaches the target regardless of bubbling.
  4. Shadow DOM retargeting. For a listener outside a shadow root, event.target is the host, so closest() from outside cannot see in. event.composedPath() gives the full path, but only for events with composed: true.

stopPropagation() stops the event at the next node but still runs the remaining listeners on the current one; stopImmediatePropagation() stops those too. Neither is preventDefault(), which is about the default action, not the path.

Curated: · Written: · Reviewed:

Q&A-9

Walk me through what stopPropagation, stopImmediatePropagation and preventDefault each stop, what each leaves running, and when using one of them is the wrong tool.

Answer

The 90-second answer. The three methods act on three different things, and conflating them is the bug. preventDefault() cancels the browser's default action for the event: the anchor navigation, the form submit, the checkbox toggle. It does not touch propagation. stopPropagation() stops the event being dispatched to the next node in the propagation path; every other listener on the current node still runs. stopImmediatePropagation() does that and also skips the remaining listeners on the current node. Only preventDefault() changes what the browser does after dispatch; only the two stop* methods change who hears about it.

The trace. <div id="outer"><button id="inner">Go</button></div>, plus a document-level listener, with a click on the button:

// Chrome 120, plain DOM
const log = (name) => () => console.log(name);
document.addEventListener('click', log('document'));
outer.addEventListener('click', log('outer-capture'), true);
outer.addEventListener('click', log('outer-bubble'));
inner.addEventListener('click', log('inner-1'));
inner.addEventListener('click', log('inner-2'));
inner-1 callsListeners that run
nothingouter-capture, inner-1, inner-2, outer-bubble, document
preventDefault()all five: default action cancelled
stopPropagation()outer-capture, inner-1, inner-2
stopImmediatePropagation()outer-capture, inner-1

Two things fall out of that table. stopPropagation() did not stop inner-2, because it is on the same node: the single most common misreading. And preventDefault() did not stop a single listener, because propagation and default action are separate phases: dispatch completes, then the browser acts on the event unless defaultPrevented is set.

Failure modes.

  1. Same-node listeners. Two handlers on one element, one calls stopPropagation() expecting to suppress the other. It doesn't. Detect: log both; both print.
  2. stopPropagation() on a link. The anchor still navigates. The default action is not propagation.
  3. preventDefault() to hide a parent handler. The parent still runs.
  4. Passive listeners. preventDefault() is a no-op and Chrome logs "Unable to preventDefault inside passive event listener invocation." Chrome has defaulted touchstart/touchmove on window, document and body to passive since Chrome 56, and wheel on root targets since Chrome 73. Check e.cancelable first: it is false for passive listeners and for events with no default action.
  5. Capture-phase stopPropagation(). Called on an ancestor's capture listener, it stops the event reaching the target at all: a much larger hammer than most people intend.
  6. Global handlers. Analytics, click-outside, router link interception and React 17+ root-container delegation all sit above your component. A stopPropagation() inside a component silently kills them, and the symptom surfaces in a different team's dashboard.

When each is the wrong tool. stopPropagation() as a substitute for preventDefault() (link, form, drag). preventDefault() to stop a parent handler. stopImmediatePropagation() to fix listener ordering: the real fix is one handler, or a guard on e.target. And stopPropagation() to isolate a third-party widget: it breaks the host page's delegated handlers, so scope the listener to the widget's root instead. Worth saying out loud: none of these stop the other events a click produces (pointerdown, mousedown, focus), and none stop the browser scrolling.

Curated: · Written: · Reviewed:

Q&A-11

What does `passive: true` on a touchmove or wheel listener actually change, and what happens if that listener calls preventDefault?

Answer

The 90-second answer. passive: true is a promise from you to the browser that this listener will never call preventDefault(). It does not change when the listener runs, what it receives, or its this: it changes whether the browser is allowed to scroll before the listener has finished. Touch and wheel scrolling are driven by the compositor thread, which can run while the main thread is busy. But if a listener on a scroll-blocking event (touchstart, touchmove, wheel) might cancel the event, the compositor cannot know the answer without asking the main thread, so it waits: scroll-start latency becomes main-thread latency. Mark the listener passive and the compositor scrolls immediately, dispatching the event to the main thread in parallel. If the listener then calls preventDefault(), the call is ignored: no exception, just a console warning in Chrome: Unable to preventDefault inside passive event listener invocation.

// Chrome 121
const onMove = (e) => { e.preventDefault(); }; // custom drag

el.addEventListener('touchmove', onMove);                    // blocks scroll
el.addEventListener('touchmove', onMove, { passive: true });  // scrolls; preventDefault ignored
el.addEventListener('touchmove', onMove, { passive: false }); // explicit opt-out

Defaults are narrower than people assume: Chrome 56 made touchstart/touchmove passive by default on window, document and document.body; Chrome 73 did the same for wheel/mousewheel on those root targets. A listener on a <div> gets no default, so pass the option explicitly. The default is engine- and version-specific: don't rely on it.

What breaks without it. A touchmove handler that only records coordinates (a swipe tracker, an analytics beacon) still costs scroll-start latency, because the browser cannot prove it won't cancel. On a page with a 200 ms long task running, the first scroll frame lands after that task, and the user sees the page freeze and then jump. That is the whole bug: not slow scrolling, late scrolling.

What preventDefault does when passive. Nothing. The event is not cancelled, the native scroll proceeds, and your drag handler fights it. If you genuinely need to cancel, there are two tools and one is better:

NeedToolCost
Cancel native scroll on an elementtouch-action: none (or pan-y) in CSSnone: the compositor knows before any event fires
Cancel conditionally at runtime{ passive: false }scroll start waits on the main thread

touch-action is the declarative form of the same information: it tells the compositor up front that this element does not scroll natively, so no listener needs to block. Reach for { passive: false } only when the decision is genuinely dynamic, a carousel that cancels only while a drag is in progress, and keep that handler short.

Failure modes. (1) The silent one: a library adds { passive: true } for you, your preventDefault becomes a no-op, and you get double-scrolling on iOS. Detect it from the Chrome warning, or from a touchmove that fires while the page still scrolls. (2) The opt-out that costs: { passive: false } on a scrollable ancestor, visible as input delay in the DevTools Performance panel's Interactions track. (3) Removal: removeEventListener matches on type, listener and capture only. passive is ignored, so addEventListener(t, f, { passive: true }) is removed by removeEventListener(t, f).

Curated: · Written: · Reviewed:

Q&A-10

Walk me through event delegation: why it works, what it costs, which events it fails on, and how you handle focus and shadow DOM boundaries.

Answer

The 90-second answer. A dispatched DOM event runs a fixed path: capture from window down to the target, the target phase, then bubble back up to window. addEventListener(type, fn) defaults to the bubble phase, so a listener on an ancestor sees every event of that type dispatched anywhere in its subtree. Delegation exploits that: one listener on a stable ancestor, and the handler decides what to do from event.target.

// Chrome 120+, no framework
list.addEventListener('click', (e) => {
  const row = e.target.closest('li[data-id]');
  if (!row || !list.contains(row)) return; // closest() can walk past the delegation root
  select(row.dataset.id);
});

Trace for a click on a <span> inside <button> inside <li> inside <ul id="list">:

capture: window → document → html → body → ul → li → button → span
target : span
bubble : span → button → li → ul → body → html → document → window

The ul listener fires once, in the bubble phase, after the button's own handlers.

What it costs. Two costs pulling in opposite directions.

Setup and memory. N listeners versus 1. Five thousand rows with a click and a keydown listener each is 10,000 listener records plus 10,000 closures; re-rendering the list means removing them all or leaking them. Delegation is one record.

Per event. The handler runs for every matching event in the subtree whether or not it is interesting, plus a closest() walk: O(depth), native, single-digit microseconds on a 5-deep tree. For click that is noise. For pointermove, input or scroll at 120 Hz it is real main-thread work; filter on the cheapest check first, or don't delegate high-frequency events to document at all.

The cost that actually bites is state. A per-element closure captures the row's object; a delegated handler recovers it from dataset or a Map keyed by id: a lookup per event and a second source of truth to keep in sync.

Which events it fails on. Delegation needs the event to reach the ancestor. Two flags decide that: bubbles (does it travel back up?) and composed (does it cross a shadow boundary?). A capture-phase listener substitutes for bubbles; nothing substitutes for composed.

EventbubblescomposedDelegate with
click, input, keydowntruetrueitself
change, submittruefalseitself in the light DOM; capture-phase or a listener inside the shadow root
focus, blurfalsetruefocusin / focusout, or a capture-phase listener
focusin, focusouttruetrueitself
mouseenter, mouseleavefalsefalsemouseover / mouseout
mouseover, mouseouttruetrueitself
load, error, abort (resource)falsefalsecapture-phase listener on document or window
scroll (on an element)falsefalsecapture-phase, or the element itself
slotchangetruefalsethe <slot>: bubbles within the shadow tree, stops at the host

The capture-phase escape hatch matters: bubbles only governs the bubble phase, so document.addEventListener('focus', fn, true) still fires for a focus on a deep input, because capture walks down through every ancestor to the target. Same trick catches <img> load failures: window.addEventListener('error', fn, true).

Shadow DOM. Two things change. First, event.target is retargeted: a listener outside a shadow root sees the host element, not the inner node, so closest() on it finds nothing useful. event.composedPath() gives the untruncated path and composedPath()[0] is the real origin: except across a closed root, where the path is cut at the host. Second, composed decides whether the event crosses at all. click, input, keydown, focus and blur are composed: true and do escape, retargeted to the host; mouseenter, mouseleave, slotchange, change, submit and any new CustomEvent('x') without composed: true never leave the shadow root, so a document-level delegated listener never sees them. If you own the component, dispatch with { bubbles: true, composed: true }.

Failure modes. A child handler calling stopPropagation() silently kills delegation for that subtree: the only symptom is the handler not firing. Events on nodes detached from the ancestor never arrive. And e.target is not always what you expect (an <svg> <use> shadow tree, the container itself), so always closest() from target rather than assuming.

Curated: · Written: · Reviewed:

Q&A-12

What does the browser and assistive technology actually do differently for `<button>` versus `<div onclick>`: focus, keyboard activation, form participation, role?

Answer

The 90-second answer. A native <button> brings four things a <div> does not: focus, keyboard activation, form participation and a role. A div has none of them, and onclick is the only thing the two share. Use <button> for an action, <a href> for navigation, and a div only for something that is not interactive.

<button type="button"><div onclick>
Tab orderin, at its DOM positionout; needs tabindex="0"
KeyboardEnter clicks on keydown, Space on keyupnothing
Role in the a11y treebuttongeneric; needs role="button"
Accessible namefrom contentsfrom contents, once the role is set
Formnone: never submits, contributes no name=valuenone
disabledleaves the tab order, blocks clicks, announced unavailableattribute is inert; needs aria-disabled plus a guard
UA stylesfont is not inherited, appearance appliesinherits everything

Form participation is where the types diverge. A <button> with no type attribute inside a form is type="submit", so it submits the form. Only submit buttons act as the form's submitter: a named submit button adds its name=value to FormData, and formaction and formnovalidate apply to it. type="button" does none of this. A div cannot be a submitter. You could call form.requestSubmit() yourself, but you would still lose the named submitter entry in FormData, formaction, formnovalidate, and the browser's own handling of constraint validation for that trigger.

Keyboard activation is more than "handle Enter". A native button fires click on Enter's keydown, repeating while the key is held, and on Space's keyup. It also consumes Space's keydown so the page does not scroll. Reproducing that on a div:

<div role="button" tabindex="0" aria-pressed="false" class="btn">Mute</div>
<script>
  const el = document.querySelector('.btn[role="button"]');
  el.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') { e.preventDefault(); activate(); }
    if (e.key === ' ') e.preventDefault();   // consume, so the page doesn't scroll
  });
  el.addEventListener('keyup', (e) => { if (e.key === ' ') activate(); });
</script>

ARIA adds no behaviour of its own. role="button" only changes what the accessibility tree reports, and the keyboard handling above is still your job. Without the role, the element is announced without a useful name or type, and a screen reader user may never reach your key handlers at all. You also owe it :focus-visible styling, because the UA focus ring was the only focus indication you got for free.

Failure modes, and how to catch them.

  1. Mouse-only div button. Unplug the mouse and tab through the page. Lint with eslint-plugin-jsx-a11y's click-events-have-key-events, and run axe, which flags interactive controls that are not focusable.
  2. tabindex="0" without role. The element takes focus but is announced as nothing, so a screen reader user lands on a nameless stop.
  3. Space scrolls the page because the keydown was not consumed. Test by focusing the control and pressing Space.
  4. disabled on a div is inert, so the click handler still runs. Use aria-disabled="true" plus a guard in the handler. Keep it focusable, so the user can discover why the control is unavailable.
  5. A <button> inside a form with no type submits the form on click. Set type="button" on every non-submitting button, or the form posts when someone opens a dropdown.

Curated: · Written: · Reviewed:

Q&A-13

Walk me through how the accessibility tree is derived from the DOM, and how ARIA roles, names and aria-hidden change what a screen reader actually sees.

Answer

The 90-second answer. The accessibility tree is a second tree the browser builds from the DOM, one node per element exposed to assistive technology. Each node carries three things a screen reader announces: a role, an accessible name, and states/properties. The browser takes the role from the explicit role attribute if present, otherwise from the element's implicit HTML semantics: <button> is a button, <h2> is a heading at level 2, <nav> is navigation. The name comes from the accessible name computation, which walks a fixed precedence list. aria-hidden="true" removes a node and its entire subtree from that tree, but it does not remove it from the tab order, and that gap is the trap.

Name computation, in order. The browser takes the first of these that yields a non-empty string:

  1. aria-labelledby: space-separated ids, concatenated in order.
  2. aria-label.
  3. The host-language label: <label for> or a wrapping <label> for form controls, alt for <img>, <caption> for tables, the text content for <button> and links.
  4. title.

So <button aria-label="Close">×</button> is announced as "Close"; the × is ignored.

What leaves the tree. Not every DOM node is exposed:

CauseIn a11y tree?Focusable?
display: nonenono
visibility: hiddennono
aria-hidden="true"no (whole subtree)yes
inertno (whole subtree)no
role="presentation"node kept, role droppedyes

The trap. aria-hidden="true" on a focusable element (a <button>, a link, anything with tabindex="0") leaves it in the tab order while hiding it from the screen reader. A keyboard user tabs to it and hears nothing; a screen-reader user cannot reach it at all. That is a WCAG 2.1 failure under 4.1.2 (Name, Role, Value), and it is the most common ARIA bug in modal and menu code.

<!-- Broken: focusable, but silent to assistive tech -->
<button aria-hidden="true" onclick="close()">Close</button>

<!-- Fixed: inert removes the background from both the tab order and the a11y tree -->
<div id="dialog" inert>…</div>

The fix is to hide the background with inert (or display: none) rather than hiding the dialog's own controls with aria-hidden. inert is supported in all current evergreen browsers.

Boundary cases. aria-hidden="false" cannot re-expose a node whose ancestor is hidden: the subtree is already gone, so the child's false is a no-op. role="presentation" strips the role but leaves the children exposed, so it is wrong for a wrapper you want gone entirely. And aria-label on a roleless <div> or <span> is ignored by most screen readers, because there is no role to name.

Curated: · Written: · Reviewed:

Q&A-17

A page's field CLS is 0.31. Walk me through the three causes you'd check first (unsized media, injected content, late webfonts) and the rendering decision that prevents each.

Answer

The 90-second answer. CLS scores movement, not slowness. A shift is recorded when a visible element's start position changes between two frames without recent user input, and each shift is scored as impact fraction × distance fraction: the union of the element's visible rects before and after, over viewport area, times the greatest distance moved over the viewport's larger dimension. The page's CLS is its worst session window (shifts less than a second apart, window capped at 5 s) reported at p75, and 0.1 is the "good" threshold. That framing already contains the fix. Either reserve the box before first layout, or move the element without re-laying out its siblings. All three common causes are failures of the first, and each is decided in the render tree, not patched at runtime.

CauseWhat the render tree doesDecision that prevents itPrice
Unsized mediaA replaced element with no intrinsic ratio lays out 0-height; when the bytes decode, the box resizes and every following block's geometry is recomputed and repaintedwidth/height attributes plus img { height: auto }, or aspect-ratio on the boxYou need the true ratio; a wrong one crops or letterboxes
Injected contentA banner, ad slot, consent bar or A/B variant inserted above painted content moves every later box down: layout is incremental and the old frame is already on screenReserve the slot (sized placeholder, min-height, aspect-ratio), or take it out of flow with position: fixedReserved-but-empty space hurts LCP and density; a fixed overlay covers content
Late webfontfont-display: swap paints the fallback immediately, then the webfont's different metrics re-measure every line boxfont-display: optional, or a metric-matched local fallback via size-adjust / ascent-overrideoptional often never shows the webfont on a first visit; overrides must be measured per font. preload only shortens the swap window, it does not close it

How big one shift is. Viewport 390×844 = 329,160 px². A 90 px cookie banner inserted at the top pushes everything down 90 px; the moved elements' union covers the viewport, so impact fraction is 1.0 and distance fraction is 90/844 = 0.107: a single banner scores ≈ 0.11, over threshold on its own. An undimensioned hero <img> is worse: it lays out 0 px tall, decodes to 390×500, everything below moves 500 px, distance fraction 500/844 = 0.592, score ≈ 0.59.

<!-- 0-height box at first layout, shift on decode -->
<img src="hero.avif" alt="Hero">

<!-- the browser derives the aspect ratio from the attributes -->
<img src="hero.avif" width="1200" height="630" alt="Hero" class="media">
// Attribute a field shift to the node that moved. The layout-shift entry
// type is Chromium-only; Safari and Firefox do not emit it, so a
// cross-browser CLS figure has to come from CrUX or a synthetic check.
new PerformanceObserver((list) => {
  for (const e of list.getEntries()) {
    if (e.hadRecentInput) continue;
    console.log(e.value.toFixed(4), e.sources?.[0]?.node);
  }
}).observe({ type: 'layout-shift', buffered: true });

Where each fix fails. A reserved slot sized by guesswork: min-height: 250px under a 320 px ad still shifts 70 px, so size the slot to the largest creative you accept. Guessed metric overrides: a 3% error in size-adjust still nudges every line box, so compare rendered widths before shipping. A client-injected A/B banner cannot be fixed in CSS: the slot has to exist in the server-rendered HTML, even as an empty element with a reserved height, or the banner has to be fixed-positioned. And converting a shifting animation from top to transform helps only because transforms composite: animating top re-lays out and still counts.

Detection. Lighthouse stops its trace before late third-party content lands, so lab CLS reads 0.00 while field CLS is 0.3: the observer above, with sources[].node, is what you attribute from. In DevTools, Rendering → "Layout Shift Regions" flashes the affected area live. Two things not to lean on: the 500 ms post-input exclusion means a shift your last tap hid is still waiting for the next visitor, and hadRecentInput filters are for the metric, not for your conscience.

Curated: · Written: · Reviewed:

Q&A-18

A click feels sluggish in the field and INP is 480 ms. Walk me through how you'd attribute that latency to a specific handler and decide what to change.

Answer

The 90-second answer. A long task is any task the browser runs on the main thread for more than 50 ms. While it runs, nothing else on that thread happens: input events queue, style and layout wait, and no frame is produced. INP is the field metric for that: the 98th percentile of interaction latencies, where one interaction runs from the input's startTime to the frame painted after its handlers finish. Good is ≤200 ms, poor is >500 ms. It replaced FID in March 2024 because FID measured only input delay to the first handler byte, not the handler or the paint.

Split the number before blaming the handler. Latency = input delay + processing time + presentation delay. Input delay is time the event sat queued behind other work; processing is your listeners; presentation delay is the render the interaction forced. A 480 ms click is often 300 ms of input delay from an unrelated long task and 60 ms of handler.

Attribution is PerformanceEventTiming, correlated with long tasks and LoAF:

// Chrome 123+
new PerformanceObserver((list) => {
  for (const e of list.getEntries()) {
    if (!e.interactionId) continue;
    console.log(e.name, e.target, {
      inputDelay: e.processingStart - e.startTime,
      processing: e.processingEnd - e.processingStart,
      presentation: e.startTime + e.duration - e.processingEnd,
      total: e.duration,
    });
  }
}).observe({ type: 'event', durationThreshold: 16, buffered: true });

new PerformanceObserver((list) => {
  for (const t of list.getEntries()) {
    console.log('longtask', t.startTime, t.duration, t.attribution?.[0]?.containerSrc);
  }
}).observe({ type: 'longtask', buffered: true });

longtask attribution gives the script URL and container, not the function, so correlate by timestamp with the event entry, then read long-animation-frame (LoAF) entries, which carry a scripts array with sourceURL, sourceFunctionName and invoker, plus renderStart and styleAndLayoutStart. That separates "my handler ran long" from "my handler forced a 200 ms layout".

PhaseFieldTypical causeFix
input delayprocessingStart - startTimeanother task holding the threadyield earlier, split tasks, move work off-thread
processingprocessingEnd - processingStarthandler CPU, sync XHR, large JSON.parsechunk, worker, cache
presentationduration - (processingEnd - startTime)forced sync layout, big DOM writebatch reads/writes, animate transform/opacity

Failure modes. Reading duration alone and blaming the handler when input delay dominates: the fix is yielding, not optimizing the handler. longtask attribution names the script, not the function, so two handlers in one bundle look identical. Event duration is rounded to 8 ms, so don't chase 4 ms deltas. INP ignores events without an interactionId and groups keyboard by key, so one bad keypress can be the reported INP.

Fix. await scheduler.yield() inside a loop keeps each task under 50 ms and lets input run between chunks; setTimeout(0) also yields but loses priority and is clamped to 4 ms after five nested levels. Yielding doesn't reduce total work: 400 ms of CPU still costs 400 ms, just spread across frames.

Curated: · Written: · Reviewed:

Q&A-21

You need a 60fps interaction: a panel sliding in, a drag, a scroll-linked effect. Walk me through how you choose between a CSS animation, the Web Animations API and a requestAnimationFrame loop, and what each costs you.

Answer

The 90-second answer. Ask what drives the value before naming a technology. If the end state is known when the animation starts (hover, entrance, a toggle, a route transition) use CSS or WAAPI. Both hand timing to the browser, and if the animated properties are transform and opacity only, the animation runs on the compositor thread and keeps its frame rate while the main thread is busy parsing, running framework work, or handling a click. If the value is computed per frame from input or state (a drag, a spring, a canvas draw) you need rAF, and you accept that the animation's frame rate is now whatever the main thread has left after style, layout, paint and every other script in the frame.

WAAPI is the middle: the same compositor path as CSS, but the timing and target are set from JavaScript, so you can start, pause, reverse, read currentTime, and await finished without a class-name dance.

CSS animation/transitionWAAPI element.animate()rAF loop
runs oncompositor, if transform/opacity onlysamemain thread
who owns timingstyle enginestyle engine, driven from JSyou
main thread blocked 200 msunaffectedunaffected~12 dropped frames
read current valuegetComputedStyle (forces style recalc)animation.currentTimeyou already have it
interrupt mid-flightnew animation starts from the computed value; can jumpcancel(), updatePlaybackRate(), commitStyles()trivial
hidden tabtimeline keeps advancingtimeline keeps advancingrAF callbacks stop
// checked against Chromium 120 / Firefox 121 / Safari 17
const panel = document.querySelector('.panel');

// compositor-friendly: transform + opacity only
const slide = panel.animate(
  [{ transform: 'translateX(0)' }, { transform: 'translateX(240px)' }],
  { duration: 200, easing: 'cubic-bezier(.2,.8,.2,1)', fill: 'forwards' }
);
// fill:'forwards' holds the end value only while the Animation object lives.
// commitStyles() writes it into inline style so cancel() doesn't snap back.
slide.finished.then(() => slide.commitStyles());
// rAF: the value isn't known up front, so the browser can't own the timing
let x = 0, last = 0, raf;
function frame(t) {
  const dt = t - last; last = t;
  x = Math.min(240, x + 0.6 * dt);   // spring-ish, input-driven
  panel.style.transform = `translateX(${x}px)`;
  raf = requestAnimationFrame(frame);
}
raf = requestAnimationFrame(frame);
// never call getBoundingClientRect() in here: it forces a synchronous layout
// before the write, every frame.

The arithmetic. 60 Hz gives 16.67 ms per frame. A 200 ms long task costs a rAF loop 12 frames; a compositor animation loses none. If the rAF callback itself costs 4 ms and style + layout + paint + other script cost 14 ms, the frame is 18 ms, 55 fps, and it degrades with anything else the page does. That is the whole argument: rAF moves work onto the thread that is already the bottleneck.

Failure modes, and how you catch each.

  1. Animating left, top, width or box-shadow. Not compositable, so every frame is style → layout → paint. Detect: the Performance panel shows Layout and Paint per frame. Fix: transform/opacity.
  2. A rAF loop that reads layout. getBoundingClientRect() or offsetHeight inside the frame forces synchronous layout before the write. Detect: "Forced reflow" annotations in the Performance panel.
  3. WAAPI without fill or commitStyles(). The effect is removed when the animation finishes and the element snaps back. Detect: a visible jump at animation end.
  4. A rAF loop that is never cancelled. It keeps running after the element is gone, and because rAF stops in a hidden tab it is not a clock either. Detect: rAF callbacks in a profile of an idle page.
  5. will-change: transform sprayed across a long list. Each promoted element is a layer with GPU memory attached. Detect: the Layers panel and memory in a heap snapshot.

When not to use each. Don't reach for rAF because it feels more controllable: for a known end state it is strictly more work on the busier thread. Don't use CSS for a value you must read back every frame. For scroll-linked effects, animation-timeline: scroll() (Chromium 115+) keeps the work off the main thread; feature-detect with CSS.supports('animation-timeline: scroll()') and keep a rAF fallback.

Curated: · Written: · Reviewed:

Q&A-22

Scroll is janky on a mid-range Android device. What do you measure first, in what order, and what does each measurement rule in or out?

Answer

The 90-second answer. Don't open a profiler first. Bound the problem, because "janky scroll on mid-range Android" is four different bugs depending on the answers: every scroll or one region, constant or degrading after 30 seconds, whole page or one sticky header, 60 Hz panel or 90 Hz. Then split the frame budget in two, main thread and compositor, because that split decides everything you do next.

Budget arithmetic first. 60 Hz is 16.67 ms per frame, 90 Hz is 11.1 ms, 120 Hz is 8.3 ms. Chrome's own style, layout, paint, composite and raster work eats into that, so a realistic main-thread budget on a mid-range Android at 60 Hz is roughly 10 ms, not 16.67.

Then the split. requestAnimationFrame only fires when the main thread is free, so rAF deltas measure main-thread frame cadence, not what the user sees:

// Chrome 120+ on Android
const deltas = [];
let last = performance.now();
requestAnimationFrame(function tick(now) {
  deltas.push(now - last); last = now;
  requestAnimationFrame(tick);
});
// after scrolling: deltas.filter(d => d > 33).length / deltas.length

Gaps in rAF deltas mean the main thread is the problem. Smooth rAF deltas with visible stutter mean the compositor is missing frames, and no amount of JS tuning will help.

MeasurementRules inRules out
rAF frame deltasmain-thread frame dropscompositor-only jank
Performance panel → Frames trackwhich frames dropped, on which thread—
LoAF / longtask entrieslong tasks overlapping frames, with script attributionwork under 50 ms
Rendering → Paint flashingper-frame repaints on scrolling contentraster and GPU cost
Rendering → Layer borders, layer countlayer explosion, GPU memory pressuremain-thread work
Rendering → Scrolling performance issuesnon-passive wheel/touch listeners—
Raster / GPU tracks in the traceraster- or GPU-bound jank—

Attributing on the main thread. longtask (50 ms threshold) is too coarse for a 16 ms budget; use Long Animation Frames, which is Chrome 123+ and reports the render phases separately:

new PerformanceObserver(list => {
  for (const e of list.getEntries())
    console.log(e.duration, e.blockingDuration, e.renderStart, e.styleAndLayoutStart, e.scripts);
}).observe({ type: 'long-animation-frame', buffered: true });

styleAndLayoutStart close to duration points at forced synchronous layout: a scroll handler reading offsetTop or getBoundingClientRect after a write. A large scripts array points at JS. Neither, with paint flashing lighting up every frame, points at paint: background-attachment: fixed, a backdrop-filter or filter: blur() on a fixed header, or a large box-shadow on scrolling content.

Attributing on the compositor. If rAF is clean, check layer count and GPU memory. will-change: transform on hundreds of list rows promotes each to its own layer; on a 3 GB device where GPU memory is shared with system RAM, that trades main-thread work for raster stalls. Then check for a non-passive touchmove/wheel listener: the compositor must wait for the main thread before it can scroll, so a listener that never calls preventDefault still costs you the frame.

Failure modes. Measure for 60 seconds, not 5, if jank grows monotonically, it's thermal throttling or the CPU governor, not your code. DevTools 4x/6x CPU throttling is a proxy: it models neither GPU nor raster nor memory, so confirm on the device through chrome://inspect. And a 60 ms long task that lands between frames costs nothing visible; don't "fix" it.

Curated: · Written: · Reviewed:

Q&A-19

Walk me through what a virtual DOM's diff and patch actually save over hand-written DOM updates, what it costs, and when you'd drop the framework and touch the DOM directly?

Answer

The 90-second answer. A virtual DOM does not make DOM writes faster. Setting el.textContent or el.style.transform is cheap; the cost is what the browser does afterwards: style recalculation, layout, paint, composite, the pipeline the critical rendering path describes. What diff-and-patch buys is a scheduling discipline: collect every change for a tick, compute the minimum set of mutations, apply them in one batch, so the browser recalculates style and layout once instead of once per write. It also stops you rebuilding subtrees, which is what loses focus, selection, scroll offset and running transitions. What it costs is JavaScript on every update: a tree walk, vnode allocation, and a heuristic that is only correct with stable keys. Hand-written DOM wins when the update is small, known and frequent: a rAF-driven transform, one cell in a 10,000-row table, a subtree a third-party widget owns. There the diff is pure overhead and you already know the node.

What the diff actually costs. React's reconciler is O(n) over the changed subtree, not the general O(n³) tree-edit distance, because it compares children positionally and matches by key only within a level. A 10,000-row list therefore costs ~10,000 comparisons per render unless rows are memoised; at 60 fps that is 600k comparisons per second of pure JS before any DOM work. Vue's patch has the same shape. The diff is a heuristic, not a proof: without stable keys, inserting at the head of a list makes the framework reuse the wrong component instances, and state lands on the wrong row.

What the patch saves. Only nodes whose output changed are touched. That matters more than the write count, because a write to a node in the render tree invalidates style for its subtree and can invalidate layout for ancestors. Rebuilding a subtree instead of updating it also resets focus, IME composition, text selection and scroll offset: the diff is what keeps those alive.

Where hand-written wins.

Update shapeFrameworkHand-written
60 Hz transform on one elementrender + diff per frameone style.transform write in rAF
1 cell changes in a 10k-row tableO(rows) unless memoisedone textContent write
Subtree owned by a chart/editor libdiff clobbers its nodesleave it alone
Whole view swaps on state changeexactly what it is foryou would rebuild the batching yourself
// rAF loop: the value is already known, so a diff is pure overhead
function tick() {
  handle.style.transform = `translateX(${x}px)`;  // one write, one composite
  x += 1;
  requestAnimationFrame(tick);
}

The cost you take on. Batching. The framework's real product is that reads and writes are separated; hand-roll updates and you must do the same, or you get forced synchronous layout: a read such as offsetHeight after a write flushes style and layout for the whole document. Illustrative: 10,000 textContent writes with no reads between them run in single-digit milliseconds; interleave one getBoundingClientRect() per iteration and the same loop takes hundreds of milliseconds. That ~10⁴ gap is why "the DOM is slow" is true only when you interleave.

Pick by update shape, not ideology: framework for the tree, refs and direct writes for the hot path.

Curated: · Written: · Reviewed:

Q&A-23

Walk me through SSR, streaming SSR and hydration: what each one does to first paint and time-to-interactive, and what hydration actually costs.

Answer

The 90-second answer. Server rendering changes when the HTML exists, not when the page becomes interactive. The browser gets real markup in the first response, parses it and paints, so FCP and LCP move earlier by roughly the time it used to take to download, parse and execute the bundle. But that markup is inert: no listeners, no state. Hydration is the client-side pass that makes it live, and it costs about what a client render costs minus DOM creation. So SSR buys paint; it does not buy interactivity. TTI is still gated on the same JavaScript.

Streaming SSR splits the response into chunks flushed as they resolve, so the browser paints the shell and each Suspense boundary as it arrives instead of waiting for the slowest query. React 18 exposes this as renderToPipeableStream (Node) and renderToReadableStream (edge). The client hydrates boundaries independently, and a click on a not-yet-hydrated boundary promotes it to the front of the queue.

FCP / LCPTTIJS shipped
CSRafter bundle download + renderafter renderfull
SSRwith the first HTML responseafter hydrationfull
Streaming SSRwith the first chunk, then per boundaryafter hydration, boundary by boundaryfull

Illustrative trace: 200 KB gzipped JS, mid-tier Android at 4× CPU throttle, Slow 4G:

  • CSR: FCP 300 ms (spinner), bundle at 600 ms, parse+compile 900 ms, render 1200 ms, LCP 1400 ms, TTI 1600 ms.
  • SSR: FCP/LCP 400 ms (content is in the HTML), bundle 900 ms, parse 1200 ms, hydration 1500 ms → TTI 1500 ms.
  • Streaming: FCP 250 ms, LCP 500 ms, TTI 1500 ms, but a click at 1000 ms on an early boundary is handled at ~1050 ms.

What hydration actually costs. Four things, and only the last is cheap:

  1. Download, parse and compile the component code: identical to CSR.
  2. Re-execute every component function to rebuild the framework's tree. This is the part people miss: hydration re-runs your render, it just skips createElement/appendChild. Cost scales with component count, not DOM size.
  3. Reconcile that tree against the existing DOM: prop diffing, event delegation set up at the root container, useId matching.
  4. Run effects. useEffect fires after hydration, so data fetches, subscriptions and third-party widgets land in the same window and often dominate it.

A 3,000-component tree at ~0.05 ms per component is ~150 ms of pure render on a mid-tier phone before reconciliation and effects. That is the number to measure, not the bundle size.

Failure modes.

  • Hydration mismatch. Server HTML and client render disagree: Date.now(), Math.random(), locale formatting, a browser-only branch. React 18 discards the server HTML and re-renders the root on the client, so you paid for SSR and got CSR. Detect: console error, onRecoverableError, React DevTools highlight-updates.
  • The uncanny valley. Fast FCP, dead page. Streaming makes it worse because the shell paints sooner. Detect: good LCP with bad INP attributed to the hydration long task.
  • Double fetching. Server fetches, then a client useEffect fetches again because the cache was never serialized. Detect: duplicate requests in the network panel.
  • TTFB regression. SSR moves work to the server; an uncached query per request can push TTFB past the point where CSR would already have painted. Detect: TTFB in field data against server render time in traces.

When not to. If the page is mostly static with a few interactive widgets, islands (Astro, Fresh) hydrate only those. Resumability (Qwik) serializes state into the HTML and skips re-execution entirely. React Server Components never ship to the client, so they cost nothing to hydrate. Plain server-rendered forms need no hydration at all.

Curated: · Written: · Reviewed:

Q&A-24

When is it correct to ship a render-blocking stylesheet or a synchronous script anyway, and what does the budget have to look like for that to be the right call?

Answer

The 90-second answer. Ship a blocking resource when the first painted frame would be wrong without it, and when that wrongness costs more than one round trip. That is the whole test, and it has two passing cases: the CSS that defines the above-the-fold frame, and a small inline script that must set state on <html> before the first paint. Theme, experiment bucket, consent gate. A blocking resource buys exactly one guarantee: the browser will not paint until it has been fetched, parsed and applied. If you don't need that guarantee, you're paying for it for nothing.

What the budget has to look like. It is a time budget converted to bytes at the p75 device and connection, not a byte budget. Lighthouse's mobile preset is the usual stand-in: 150 ms RTT, 1.6384 Mbps (204.8 KB/s), 4× CPU slowdown. A TCP connection's initial congestion window is 10 segments of 1460 bytes, so roughly 14 KB arrives in the first round trip after the request.

Blocking resourceBudgetWhy that number
Stylesheet≤ 14 KB uncompressed, one file, no @importfits the initial congestion window, so it lands in one RTT
Inline script≤ 2 KB, no network fetch, ≤ 5 ms execution at 4× throttlealready in the HTML; costs parse + execute only
Blocking set, total≤ 1 RTT added to FCPa second round trip is a cliff, not a slope

14 KB at 204.8 KB/s is 68 ms of transfer; add the 150 ms RTT and that stylesheet costs about 220 ms of FCP. A second blocking stylesheet that doesn't fit the window costs another RTT, roughly 370 ms, which is why the budget is "one round trip", not "one file".

<!-- inline, with a CSP nonce; an external file would add an RTT -->
<script nonce="…">
  try {
    const t = localStorage.getItem('theme');
    if (t === 'dark' || t === 'light') document.documentElement.dataset.theme = t;
  } catch {} // Safari private mode throws; fall through to prefers-color-scheme
</script>

documentElement exists as soon as the parser has seen <html>, so this runs before any body content is parsed and before the first paint. The HTML spec's blocking="render" attribute lets you opt into render-blocking explicitly for a stylesheet you would otherwise load async; support is not universal, so treat it as a declaration of intent rather than a portable mechanism.

Failure modes. The blocking set grows past one round trip: a second stylesheet, an @import, a font the first paint waits on. Detect it as the gap between "Parse HTML" and the FCP marker in the Performance panel, or with Lighthouse's "Eliminate render-blocking resources" audit, which reports the milliseconds saved. The inline script throws, Safari private mode throws on localStorage, and you paid the blocking cost and still got the flash; catch it, and check a WebPageTest filmstrip for a flash frame. The blocking script reads layout (getBoundingClientRect), forcing style and layout before paint; the Performance panel flags "Forced reflow". The blocking CSS is a whole framework rather than critical CSS; the Coverage panel shows the unused percentage.

When not to. If the flash is invisible, the script is pure cost. If prefers-color-scheme plus <meta name="color-scheme"> covers the case, use CSS: the script is only needed when the stored choice can diverge from the OS setting. If the resource is below the fold, load it async and accept the late paint. Enforce the budget in CI per route (Lighthouse CI budget.json), on the p75 profile, not on your laptop.

Curated: · Written: · Reviewed:

Q&A-25

A rich animated landing page has a 2.0s LCP budget on 4G. Walk me through how you attribute the LCP time across the critical path, decide what to cut, and what you measure to defend the cut.

Answer

The 90-second answer. A 2.0s LCP budget is not a page-weight budget. It is a deadline for one element, the largest image or text block in the viewport, and it decomposes into four measurable parts: TTFB, resource load delay, resource load duration, element render delay. I attribute the current page across those four before I cut anything, because the part that is over budget decides what goes. On a 4G profile (Lighthouse's mobile preset: 150 ms RTT, 1.6 Mbps, 4× CPU slowdown) the transfer rate is roughly 205 KB/s, so a 200 KB hero costs about 1.1 s of the 2.0 s before anything else happens. That single number is what makes the conversation concrete.

The decision rule: anything that runs before first paint and is not the LCP element's own bytes gets deferred or removed; anything that changes when the LCP element paints gets cut or moved after it. Animation is usually the first casualty, not because animation is expensive, but because an intro that starts the hero at opacity: 0 moves LCP to the frame where opacity becomes non-zero. Chrome does not count an element with opacity: 0 as contentful, so the fade-in is the LCP time.

The arithmetic. Illustrative, on the mobile preset:

StageBeforeAfter
TTFB400 ms400 ms
Load delay (hero discovered)620 ms: set by JS after hydration0 ms: <link rel=preload> + fetchpriority="high" in the initial HTML
Load duration200 KB JPEG ≈ 1.1 s60 KB AVIF ≈ 440 ms
Render delay300 ms: animation lib parse + first frame120 ms
LCP~2.4 s~0.96 s

What I cut, in order. loading="lazy" on the hero: it is the LCP element, so lazy-loading it buys nothing and adds load delay. The intro animation's pre-paint phase: render the hero at opacity 1, then animate it; same design, no LCP cost. The animation library, if it is parsed before first paint: 30 KB gzipped on a 4× slowed CPU is ~100 ms of main-thread parse and execute competing with the paint, whereas a CSS @keyframes on transform/opacity runs on the compositor and costs the main thread nothing. Third-party tags that execute before first paint.

What I measure to defend it. The four parts, from the LCP entry plus the resource timing entry for the LCP resource:

// Chrome 120+
const lcp = await new Promise(res => {
  new PerformanceObserver((l, o) => { res(l.getEntries().at(-1)); o.disconnect(); })
    .observe({ type: 'largest-contentful-paint', buffered: true });
});
const nav = performance.getEntriesByType('navigation')[0];
const res = performance.getEntriesByName(lcp.url)[0];
const ttfb        = nav.responseStart;
const loadDelay   = res.startTime - ttfb;
const loadDuration = res.duration;
const renderDelay = lcp.startTime - res.responseEnd;

For a text LCP element there is no resource, so load delay and duration are zero and the budget is TTFB plus render delay. Two gotchas: renderTime is 0 for cross-origin images without Timing-Allow-Origin, so you fall back to loadTime and overstate render delay; and LCP stops updating after the first user interaction, so a scroll during load truncates the measurement. Field p75 from RUM is the number the budget is written against: a lab Lighthouse run is the debugging tool, not the evidence.

Failure modes. Hero discovered late: load delay > 0, visible in the waterfall as the image request starting after the JS bundle. Fade-in hero: LCP startTime matches the animation's end frame, not the image's load. Font-blocked text LCP: font-display: block holds the heading invisible, render delay is large and the LCP element is a heading. Main-thread contention: long tasks overlapping the LCP window, caught with a longtask observer or the trace's main-thread track.

When not to cut. If the LCP element is text, image work buys nothing. And if the animation is the product, the honest move is to raise the budget or move it behind an interaction, not to claim a 2.0s LCP and a pre-paint animation coexist.

Curated: · Written: · Reviewed: