← Back to JavaScript, page 5

javascript-0089 · Hard senior

How does the browser turn HTML into pixels, and what are reflow, repaint, and layout thrashing?

The browser builds the DOM and CSSOM, combines them into a render tree, computes geometry in layout (reflow), paints pixels into layers, and composites the layers on the GPU. Changing geometry triggers layout, changing appearance triggers paint, and transform or opacity changes can often skip both. Layout thrashing is alternating DOM writes and layout reads in a loop, which forces repeated synchronous layouts.

Full answer

The rendering pipeline has these main stages. The browser parses HTML into the DOM and CSS into the CSSOM. Together they form the render tree of visible boxes with computed styles. Layout, also called reflow, calculates each box's size and position. Paint turns boxes into drawing instructions and pixels in one or more layers. Compositing combines the layers, often on the GPU, into the final frame.

What a change triggers depends on the property. Changing width, height, margin, top, font size, or adding and removing elements affects geometry and can force layout of a large part of the page, followed by paint and composite. Changing color or background only needs paint and composite. Changing transform and opacity on a layer that is already promoted can need only compositing, so these are the cheap properties for animation.

The browser batches style and layout work and normally performs it once per frame, just before painting. Reading a geometry value such as offsetHeight, getBoundingClientRect(), or scrollTop after a write forces the browser to compute layout right now so the value is correct. This is a forced synchronous layout. Layout thrashing is doing that repeatedly, for example in a loop that sets a width and then reads a height for each element, producing one layout per iteration instead of one in total.

Fixes: read all the values first and then write all the changes (batching); build changes off the document in a DocumentFragment; toggle a class instead of many inline styles; animate with transform and opacity; use requestAnimationFrame to schedule visual work at frame time; and use content-visibility or virtualization for long lists. Use the Performance panel to see the layout and paint cost.

Frames should fit in about 16 ms at 60 frames per second, which includes JavaScript, style, layout, paint, and composite work.

javascript
// A model of the browser's layout rule, not a measurement of a real browser.
class LayoutModel {
  constructor() {
    this.dirty = false;
    this.layouts = 0;
  }
  write(box, height) {
    box.height = height; // changing geometry marks the layout as stale
    this.dirty = true;
  }
  read(box) {
    if (this.dirty) {
      this.layouts += 1; // reading forces a synchronous layout when it is stale
      this.dirty = false;
    }
    return box.height;
  }
  frameEnds() {
    if (this.dirty) {
      this.layouts += 1; // otherwise layout runs once, just before painting
      this.dirty = false;
    }
  }
}

const makeBoxes = () => Array.from({ length: 100 }, () => ({ height: 10 }));

function thrashing() {
  const model = new LayoutModel();
  const boxes = makeBoxes();
  for (const box of boxes) {
    model.write(box, model.read(box) + 5); // read, write, read, write ...
  }
  model.frameEnds();
  return model.layouts;
}

function batched() {
  const model = new LayoutModel();
  const boxes = makeBoxes();
  const heights = boxes.map((box) => model.read(box)); // all reads first
  boxes.forEach((box, i) => model.write(box, heights[i] + 5)); // then all writes
  model.frameEnds();
  return model.layouts;
}

console.log('layouts with alternating read and write:', thrashing());
console.log('layouts with reads batched before writes:', batched());

const frames = [];
function schedule(callback) {
  frames.push(callback); // stands in for requestAnimationFrame
}
const model = new LayoutModel();
const box = { height: 10 };
schedule(() => model.write(box, 50));
schedule(() => model.write(box, 80));
frames.splice(0).forEach((callback) => callback());
model.frameEnds();
console.log('two writes in one frame cost layouts:', model.layouts, '| final height:', box.height);

const cost = {
  'width, height, margin': ['layout', 'paint', 'composite'],
  'color, background': ['paint', 'composite'],
  'transform, opacity (promoted layer)': ['composite'],
};
for (const [property, stages] of Object.entries(cost)) console.log(property.padEnd(38), '->', stages.join(' + '));

Run with Node.js v24.22.1 as js-89.js; two runs gave identical output. Output: layouts with alternating read and write: 100 layouts with reads batched before writes: 1 two writes in one frame cost layouts: 1 | final height: 80 width, height, margin -> layout + paint + composite color, background -> paint + composite transform, opacity (promoted layer) -> composite

Key points

  • Pipeline: DOM and CSSOM, render tree, layout, paint, composite.
  • Geometry changes trigger layout; appearance changes trigger paint; transform and opacity can skip both.
  • Reading layout values after a write forces a synchronous layout.
  • Layout thrashing is alternating reads and writes in a loop; batch reads before writes.
  • Use requestAnimationFrame, class toggles, fragments, and virtualization to reduce work.

Common mistakes

  • Reading offsetHeight or getBoundingClientRect inside a loop that also writes styles.
  • Animating top, left, or width when transform would avoid layout.
  • Assuming every CSS change costs the same.
  • Optimizing without profiling, and promoting too many elements to their own layers, which uses memory.

Follow-ups

  • What does the will-change property do, and what are the risks of overusing it?
  • How do requestAnimationFrame and requestIdleCallback differ?
  • Which metrics (LCP, CLS, INP) are affected by layout work?

Tips

  • Walk through the pipeline in order and say which stage each type of change triggers.
  • Define layout thrashing with the read-write loop and give the batching fix.
  • Mention transform and opacity for animation and the Performance panel for evidence.