In the browser, when we change the size, position, color and other attributes of an element, it will cause the browser to recalculate and recalculate the page. rendering operations. Among them, these two stages are called CSS reflow (reflow) and repaint (repaint).
CSS reflow means that when the size, layout, or position of a DOM element changes, the browser needs to recalculate the geometric properties of the element and rebuild the rendering tree of the page. Reflow will definitely cause redraw, but redraw will not necessarily trigger reflow.
CSS redraw means that when the change of element style does not affect the layout, the browser only needs to redraw the element without recalculating the layout. For example, changing the color of an element will only cause a redraw and will not trigger reflow.
Since reflow and redrawing require the browser to recalculate and render the page, they will cause performance losses. Therefore, when writing code, you should try to avoid frequent reflow and redrawing. You can take the following optimization measures:
- Avoid frequent modification of DOM styles.
- Use transform to replace operations such as top/left that cause reflow.
- Use document fragment (DocumentFragment) to perform DOM operations, and finally add it to the document at once.
- Avoid using CSS expressions as they cause the browser to recalculate each time.
- Avoid frequently reading layout information or using attributes such as offset series, which will force the browser to reflow.
In short, writing code properly and reducing reflow and redraw operations can improve page performance and user experience.