Reflow vs repaint in one screen
The one-page summary of the lesson Reflow vs repaint. It states the answers, so if you want them to stick, play the lesson first: it makes you predict before it explains.
The points
- Reflow = layout running again. Repaint = paint without layout.
- A style write only marks layout as out of date.
- Reading a size after a write forces layout now: offsetHeight, offsetWidth, clientWidth, scrollTop, getBoundingClientRect(), and sizes read through getComputedStyle().
- Write, read, write, read in a loop: layout every turn (thrashing).
- Read everything first, then write everything.
- Colour, background and shadow changes repaint without reflow.
- Prefer CSS layout (grid, flex) to measuring in JavaScript.
What catches people out
- getBoundingClientRect() is not a cheaper read: it forces layout too.
- A read in a library or helper still counts.
- Reads with no write between them share one layout.
The wrong idea, and the right one
Often believed: Layout happens once per frame, whatever my script does. Reading a size like offsetHeight is free: it is just a property.
What really happens: A style write only marks layout as out of date. Reading a size such as offsetHeight or getBoundingClientRect() after a write forces the browser to lay out right then. Alternate writes and reads in a loop and layout runs on every turn. Read everything first, then write.
Step by step
- Symptom. Code that looks cheap can freeze the page.
- A write marks it stale. A write only marks layout as out of date.
- Layout once, at the end. Normally, layout runs once, after the script.
- A read forces layout. Reading a size after a write forces layout immediately.
- Thrashing. Write, read, write, read: layout on every turn. This is layout thrashing.
- Batched. Batch reads together and writes together.
- Break it: colour only. Repaint without reflow is the cheaper path.
- Agent bug. Never read a size right after writing a style, inside a loop.
- Recap. Read first, then write.
Sources
- web.dev/articles/avoid-large-complex-layouts-and-layout-thrashing
- gist.github.com/paulirish/5d52fb081b3570c81e3a
- developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight
- developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
- drafts.csswg.org/cssom-view/
- developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-rows
- developer.mozilla.org/en-US/docs/Web/API/ResizeObserver