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

  1. Symptom. Code that looks cheap can freeze the page.
  2. A write marks it stale. A write only marks layout as out of date.
  3. Layout once, at the end. Normally, layout runs once, after the script.
  4. A read forces layout. Reading a size after a write forces layout immediately.
  5. Thrashing. Write, read, write, read: layout on every turn. This is layout thrashing.
  6. Batched. Batch reads together and writes together.
  7. Break it: colour only. Repaint without reflow is the cheaper path.
  8. Agent bug. Never read a size right after writing a style, inside a loop.
  9. Recap. Read first, then write.

Sources

Play the lesson: Reflow vs repaint