Real name boards: interleaved reads and writes, or all reads then all writes: how many layouts does each force? Every read is timed with performance.now. An…
Why it matters
Forced layout is one of the most common sources of jank: animation in JavaScript, old libraries, “measure then set” code inside a loop. One wrong loop can add a dozen milliseconds to a frame and make scrolling or animation stutter. The pattern is easy to fix once it is recognised.
The key idea
Reading geometry after a write forces layout in the middle of a script
Common mistakes
Thinking el.style.width = … alone is slow Writing a style is cheap and put off: it only marks layout dirty. What costs is reading geometry after it, which forces layout to be worked out right then. A run of writes with no reads is safe.
Keeping offsetWidth in a variable but still inside the read-write loop A variable filled again every round still reads after the previous round’s write, so layout is still forced every time. Separate the phases: all reads first (or one read before the loop), all writes after.
Forgetting that getComputedStyle() and scrollTop force it too Not only offsetWidth: getBoundingClientRect(), clientHeight, scrollTop, getComputedStyle(el).width and friends force layout when read after a write. el.style.width does not, because it is only the style that was written. The cure is the same: read all, then write all, or split the phases with requestAnimationFrame.
Try it in this playground
Widen 120 boards interleaved Nearly one forced layout per board, and the stopwatch records its price.
Switch to read all, then write all Zero layouts forced inside the loop, one at the end.
Writes only, no reads Writing styles is cheap: nothing is forced.
Compare getComputedStyle(el).width and el.style.width One needs layout, the other only reads the style that was written.