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.