Skip to the page

JavaScript cost and the main thread · mid

Rendering work: style, layout, paint, composite and layout thrashing

Each frame the browser may recalculate style, run layout, paint and composite; changing geometry triggers layout (expensive), changing colours triggers paint, and transform/opacity can be composite-only, while reading layout right after writing styles forces a synchronous layout (layout thrashing).

The notes

What you must know

  • Pipeline per frame: JS -> style -> layout -> paint -> composite. Layout (geometry) costs more than paint (pixels), which costs more than composite (moving layers on the GPU).
  • Layout triggers: width, height, top, left, margin, padding, font-size, adding/removing DOM nodes. Paint-only: color, background-color, box-shadow. Composite-only (usually): transform, opacity.
  • Forced synchronous layout: you change a style, then read offsetHeight / getBoundingClientRect / scrollTop in the same task, so the browser must do layout now. In a loop this is layout thrashing.
  • Fix: read all values first, then write all changes; or schedule writes in requestAnimationFrame; or use a library that batches.
  • Animate transform and opacity; use will-change sparingly (each layer costs memory).
  • content-visibility: auto skips rendering work for off-screen sections (Baseline since 2024); give them contain-intrinsic-size to avoid scrollbar jumps.
  • Big DOMs (many thousands of nodes) make every style and layout pass slower, which hurts INP's presentation delay.

The red pen

Common traps: mistake → fix

  • Mistake: "Repaint always causes reflow"

    Fix: it is the other way: layout usually causes paint, but paint-only changes do not need layout.

  • Mistake: "will-change on everything makes animations fast"

    Fix: too many layers use lots of memory and can slow things down.

  • Mistake: "Reading offsetHeight is free"

    Fix: after a style write it forces a synchronous layout.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between reflow (layout), repaint and composite?
  2. What is layout thrashing? Show code that causes it and fix it.
  3. Which CSS properties are cheap to animate and why?
  4. A long list page has INP problems with a huge presentation delay. What rendering fixes would you try?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview