Lesson 1 · The web platform, in depth

The rendering pipeline and performance

Style, layout, paint and composite, and how to stop forcing layout.

About 30 minutes

Tab indents. Press Escape, then Tab, to leave the editor.

Every visual change you make goes through the same machinery: the browser recomputes styles, works out geometry, records drawing commands, rasterizes them and composites the result onto the screen. Most jank is not slow JavaScript in the abstract; it's JavaScript that makes that machinery run more often, or more of it, than the frame needs. This lesson walks the pipeline, shows the one pattern that causes most avoidable layout work, and defines the metrics you'll be judged on.

The pipeline, stage by stage

The names below follow Chromium's RenderingNG, but Gecko and WebKit have the same broad shape. What differs is which work happens off the main thread.

Step by step

From a DOM change to pixels

Script and events

Your code mutates the DOM or CSSOM: sets el.style.width, toggles a class, appends nodes. Nothing is drawn yet. The browser marks the affected parts of the tree as needing style and layout and carries on.

1 / 5

The practical rule: a change costs the stage it invalidates plus every stage after it. Geometry changes (width, top, font-size, inserting text) cost layout, paint and composite. Visual-only changes (color, box-shadow, background) cost paint and composite. A change to transform or opacity on an element that already has its own compositing layer costs composite only.

The frame budget

A display refreshing at 60 Hz shows a new frame about every 16.7 ms; at 120 Hz, every 8.3 ms. Everything the main thread does between frames (your event handlers, timers, framework rendering, and the style, layout and paint the browser runs for you) has to fit inside that window, or the frame is late and the animation or scroll visibly stutters. The Long Tasks API and the Performance panel both call a main-thread task over 50 ms "long", which is the threshold where input responsiveness starts to suffer noticeably, not the threshold for smooth animation.

Forced synchronous layout

Normally the browser is lazy: you write styles, it batches the work and runs style and layout once, just before the next frame. That changes the moment you read a value that depends on layout while layout is dirty. To answer el.offsetWidth truthfully the engine must run style and layout right now, synchronously, in the middle of your script. This is a forced synchronous layout (Chrome DevTools calls it a forced reflow).

Properties and methods that force it include offsetTop/Left/Width/Height, clientWidth/Height, scrollTop, scrollHeight, getBoundingClientRect(), getClientRects(), innerText, focus() (it may need to scroll), and getComputedStyle() for layout-dependent values such as width.

One forced layout is often fine. The disaster is alternating reads and writes in a loop, layout thrashing:

// Each iteration writes (dirtying layout) and then the next iteration reads (forcing it).
for (const card of cards) {
  card.style.height = card.offsetWidth * 0.75 + 'px'
}

With N cards that's N layouts in one task instead of one. Each of those layouts may also be large, because a height change on one card can reflow everything after it. The fix is structural: do all the reads first, then all the writes.

const widths = cards.map((card) => card.offsetWidth) // one layout, then cached
cards.forEach((card, i) => {
  card.style.height = widths[i] * 0.75 + 'px' // writes only: layout is deferred to the frame
})

In a larger codebase, reads and writes come from different components that don't know about each other. The usual tools: schedule writes in requestAnimationFrame so they run together just before the frame, keep a read phase and a write phase (the pattern behind libraries like fastdom), or avoid the read entirely with ResizeObserver, which delivers sizes after layout has already run.

Challenge

Stop the thrashing

doubleWidths(bars) should make every bar twice as wide as it is now. The starter version alternates a read and a write for each bar, which forces a layout per bar.

Rewrite it so every read happens before any write. Keep using the readWidth and writeWidth helpers: they record the access pattern in trace so the checks can see it. (In real code you'd use getBoundingClientRect() and style.width directly.) Press Run, then Double to see the trace and the time taken.

Console
  1. Nothing logged yet.
  • Every bar ends up twice as wide as before
  • All reads happen before the first write

With five tiny bars the timing difference is noise. Scale the same pattern to a few hundred list rows with real text and it's the difference between a 2 ms handler and a 200 ms one, and the trace tells you why before the profiler does.

Compositor-only properties

transform and opacity are special because the compositor can apply them to an existing layer without involving the main thread. A CSS animation or transition, or a Web Animations API animation, of those properties can keep running smoothly even while the main thread is busy with a long task. Animate left, top, width or margin instead and every frame needs layout and paint on the main thread, which is exactly where your JavaScript also runs.

For this to work the element needs its own compositing layer. Engines promote animated transform/opacity elements automatically once the animation starts; will-change: transform promotes ahead of time so the first frame doesn't pay for layer creation. Layers aren't free: each costs GPU memory for its tiles and adds compositing work, and promoting an element can force elements painted above it into layers too ("layer explosion"). Apply will-change to the few elements that are about to animate, not to *.

Question

Quick check

You need a sidebar to slide in smoothly on a low-end phone while the app is still parsing a large JSON response on the main thread. Which approach holds frame rate best?
Pick an answer.

Skipping work you can't see: content-visibility

Long pages pay style and layout for content far below the fold. content-visibility: auto lets the browser skip style, layout and paint for an element's subtree while it is off-screen (it applies layout, style and paint containment), and render it when it approaches the viewport. It's supported in current Chromium, Firefox and Safari.

.article-section {
  content-visibility: auto;
  /* Placeholder size while skipped; "auto" remembers the real size once rendered. */
  contain-intrinsic-size: auto 600px;
}

Without contain-intrinsic-size a skipped element is laid out as if empty, so the scrollbar jumps as sections render. Skipped content is still in the DOM and the accessibility tree and still findable with find-in-page. The trade-off is that reading layout (offsetHeight, getBoundingClientRect) inside a skipped subtree forces it to render, which throws the saving away. For subtrees that should never render until shown, content-visibility: hidden keeps the rendering state cached for quick re-show, unlike display: none.

Measuring instead of guessing

performance.now() gives a monotonic, high-resolution timestamp relative to the page's time origin (browsers deliberately coarsen its resolution as a Spectre mitigation, less so on cross-origin isolated pages). Two traps:

  1. Timing writes measures nothing. Setting styles is cheap; the cost lands later, at the next rendering opportunity, outside your timer. Either read a layout property inside the timed window to flush (as the playground does), or measure in the Performance panel.
  2. Use marks for code that spans tasks. performance.mark('filter-start') and performance.measure('filter', 'filter-start') show up as named bars in the Performance panel's Timings track.

In the Performance panel, record with CPU throttling on (a 4× or 6× slowdown is closer to a mid-range phone than your laptop). Look for long tasks (marked with a red corner), purple Recalculate Style and Layout events inside your script's call stack (with a warning that links to the line that forced them), and green Paint events. The Layout shifts track shows which nodes moved.

The metrics: LCP, INP, CLS

Core Web Vitals are assessed at the 75th percentile of real page loads, separately for mobile and desktop. Lab tools approximate them; field data (the Chrome UX Report or your own RUM with the web-vitals library) is what counts.

MetricWhat it measuresGoodPoor
LCP, Largest Contentful PaintTime from navigation start until the largest image, video poster or text block in the viewport is rendered. Candidates stop being recorded once the user interacts (tap, click, key press, scroll).≤ 2.5 s> 4 s
INP, Interaction to Next PaintFor every click, tap and key press during the page's life, the time from input to the next frame being presented: input delay + event processing + presentation delay. Reports the worst interaction (ignoring one outlier per 50 interactions on busy pages). Replaced FID as a Core Web Vital in March 2024.≤ 200 ms> 500 ms
CLS, Cumulative Layout ShiftThe largest session window of unexpected layout shifts: shifts less than 1 s apart, window capped at 5 s. Each shift scores impact fraction × distance fraction. Shifts within 500 ms of user input don't count.≤ 0.1> 0.25

How they map to the pipeline: LCP is usually network and render-blocking resources first, then main-thread time before first paint. INP is almost entirely main-thread contention: long tasks delaying the handler, heavy handlers, and expensive style/layout/paint after them. CLS is layout that happens late: images without width/height or aspect-ratio, injected banners, web fonts swapping in with different metrics.

Question

Quick check

A button's click handler takes 40 ms, but users report the app feels sluggish when they tap it. The Performance panel shows a 300 ms task from a third-party script running just before the handler. What does INP attribute those 300 ms to?
Pick an answer.

Recap

  • A change costs the stage it invalidates and every later one: geometry → layout + paint + composite; visual → paint + composite; transform/opacity on a layer → composite only.
  • Reading layout (offsetWidth, getBoundingClientRect()…) after a write forces synchronous layout. Batch all reads, then all writes, or use requestAnimationFrame and ResizeObserver.
  • Animate transform and opacity so the compositor can keep frames coming while the main thread is busy; use will-change sparingly.
  • content-visibility: auto plus contain-intrinsic-size skips rendering work for off-screen content.
  • Measure with performance.now()/marks and a throttled Performance recording, and judge outcomes by field LCP (≤ 2.5 s), INP (≤ 200 ms) and CLS (≤ 0.1) at p75.

Finished this lesson?

Mark it complete to track your progress on this device.

Next: The event loop