Reflow, Repaint & Layout Thrashing
The secret cause of laggy websites. Discover why Repaint is fast but Reflow is expensive, understand the lethal performance killer known as Layout Thrashing (Forced Synchronous Layout), and learn how batching DOM reads and writes saves 60fps frame rates.
1. Mental Model: Knocking Down Walls (Reflow) vs. Repainting Walls (Repaint)
Reflow (Layout): Heavy Structural Renovation
Knocking down a structural wall in a house. The roof settles, plumbing pipes must be rerouted, adjacent rooms shrink, and all furniture must be repositioned. Triggered by changing width, height, font-size, or adding/removing DOM elements.
Repaint: Changing Wall Paint Color
Painting your bedroom wall from yellow to blue. Zero walls move; furniture remains exactly where it was. Triggered by changing color, background-color, or visibility. Much faster than reflow!
2. The Deadly Crime: Layout Thrashing (Forced Synchronous Layout)
Browsers normally batch DOM writes and execute them once at the end of the 16.6ms frame. However, if you write a style and then immediately ask for a geometric dimension in JavaScript, you force the browser to execute an emergency synchronous reflow on the spot!
3. Interactive Studio: Simulate Layout Thrashing vs. Batched Loop
First-Year Student Traps: Reflow & Repaint
- 1.Properties that Trigger Forced Reflow: Accessing any of these properties right after writing style changes will force an emergency reflow:
offsetWidth,offsetHeight,scrollTop,getBoundingClientRect(), andgetComputedStyle(). - 2.FastDOM / requestAnimationFrame: If you must mutate DOM styles based on measurements, wrap reads in the current tick and wrap writes inside
requestAnimationFrame(() => { ... })to let the browser execute them at the start of the next refresh cycle.
GPU Acceleration & will-change
Promote elements into independent GPU compositing layers without causing memory leaks.