Introduction to Repaint & Reflow and how to optimize it

Introduction to Repaint & Reflow and how to optimize it

Repaint and reflow are two key processes when the browser renders the page.

  1. Repaint:

    • Redrawing means that when the style of elements changes but does not affect the layout, the browser will redraw these elements.
    • For example, modifying attributes such as color and background will not cause changes to the page layout, but will only trigger redrawing.
    • Redrawing is relatively cheap as it only requires redrawing the affected parts.
  2. Reflow:

    • Reflow means that when the page layout changes, the browser will recalculate the geometric properties of the elements and then rebuild the page layout tree (Layout Tree).
    • Operations such as changing the size and position of elements, adding or removing elements, etc. will cause reflow.
    • Reflow is relatively expensive because it triggers a reflow of the entire page, and other affected elements will also be reflowed and repainted.

Methods to optimize redraw and reflow:

  • Reduce access to the DOM: Multiple accesses and modifications to the DOM will result in multiple reflows and redraws. Multiple operations can be combined into one operation to reduce direct access to the DOM.
  • Modify styles in batches: Combine multiple style modifications into one operation by adding a class name or modifying the style attribute of an element.
  • Use document fragments (DocumentFragment): Use document fragments to perform multiple DOM operations, and then add them to the document at once to reduce the number of reflows.
  • For elements that require frequent operations, you can first remove them from the document flow (display: none), and then reinsert them into the document after the operation is completed.
  • Use CSS3 animations and transitions instead of JavaScript operations to reduce the impact on layout.
  • Use transform and opacity to achieve animation effects, which can enable GPU acceleration and reduce reflow and redrawing.
  • Avoid frequently reading property values ​​that cause reflow, such as offsetTop, offsetLeft, clientWidth, etc.

In short, the key to optimizing redraw and reflow is to reduce operations on the DOM, try to batch style modifications, and avoid triggering reflow and redraw frequently. This improves page performance and user experience.

Guess you like

Origin blog.csdn.net/rqz__/article/details/132859242