Middle
How can Reflow (Layout) and Repaint be optimized to avoid sequentially triggering Layout-Paint-Layout-Paint?
sobes.tech AI
Answer from AI
To optimize Reflow (Layout) and Repaint and avoid the Layout-Paint-Layout-Paint chain, it is necessary to minimize the number of changes that trigger style recalculations and repainting.
Main recommendations:
- Group DOM and style changes: make all changes in one cycle so that the browser can perform Layout and Paint only once.
- Use
requestAnimationFramefor animations and changes to synchronize them with the rendering cycle. - Avoid reading properties that cause forced reflow (e.g.,
offsetWidth,clientHeight) immediately after style modifications — this causes synchronous Layout. - Use CSS classes for bulk changes, rather than changing styles one property at a time.
- Use
will-changeto inform the browser which properties will change to optimize rendering.
Example of bad practice:
el.style.width = '100px';
console.log(el.offsetWidth); // forced reflow
el.style.height = '200px';
Optimal:
el.style.width = '100px';
el.style.height = '200px';
console.log(el.offsetWidth); // one reflow