← Lessons

quiz vs the machine

Silver1050

Frontend

The DOM and Reflow

Why reading and writing layout in the wrong order makes pages janky.

4 min read · intro · beat Silver to climb

The DOM

The DOM is a tree of nodes the browser builds from your HTML. JavaScript can read and mutate this tree, and every mutation can affect what the browser must draw.

Reflow and repaint

  • Reflow (layout) recalculates the geometry of elements: positions and sizes.
  • Repaint fills in pixels: colors, shadows, text.
  • Reflow is more expensive because it can cascade to ancestors and siblings.

Layout thrashing

Reading a layout property like offsetHeight forces the browser to flush pending changes so the value is accurate. If you interleave reads and writes in a loop, you trigger many forced reflows, a pattern called layout thrashing.

  • Batch all reads first, then all writes.
  • Use requestAnimationFrame to schedule writes before the next paint.
  • Prefer transform and opacity, which can skip layout entirely.

Key idea

Group DOM reads and writes separately so you avoid forced synchronous reflows that stall the frame.

Check yourself

Answer to earn rating on the learn ladder.

1. Why is reflow usually more costly than repaint?

2. What triggers layout thrashing?