CSS Reflow (Reflow) and Repaint (Repaint)

1. Introduction

Reflow and redrawing in CSS refers to the process in which the browser redraws and displays the page when the HTML or CSS nodes change. Reflows and repaints cause browser performance degradation and should be minimized.

2. The process of browser parsing page

Browser parsing pages are mainly divided into the following processes:

1. Parse HTML to form HTML DOM tree

2. Parse CSS and generate CSS rule tree

3. Combine HTML DOM tree with CSS rule tree (attachment) to generate Render tree

4. Layout Render tree (layout/reflow), responsible for the calculation of the size and position of each element

5. Draw Render tree (painting), draw page pixel information

6. The browser sends the information of each layer to the GPU, and the GPU synthesizes each layer and displays it on the screen

3. The occurrence stage of reflow and redrawing

When HTML or CSS changes, it will cause the browser to re-parse the HTML DOM tree and CSS state tree, resulting in a re-layout (layout) and rendering (repaint).

Reflow: It is layout or reflow, which refers to re-layout. It generally means that the size, position, structure, content, font size, etc. of the element have changed and need to be re-parsed.

· Repainting: Repaint means redrawing, when the change of page element style does not affect the position of the element in the document flow. Generally, the color of the element, the background color and other appearances change, and it needs to be re-parsed.

The cost of reflow is higher than that of redrawing, because as long as it is reflow, it must be redrawn.

4. Some optimization schemes

1. Avoid changing styles item by item, and use class to change styles uniformly to reduce reflow.

2. Avoid circular manipulation of the DOM.

3. Try to avoid obtaining attributes such as offsetXXX, scrollXXX, and clientXXX multiple times. If it cannot be avoided, use variable storage to minimize backflow.

4. The animation effect is applied to elements whose position is absolute or fixed. Because the animation is separated from the document flow, reflow and redrawing are reduced.

5. Enable GPU acceleration for animation. The essence of enabling css3 animation acceleration is that the transform attribute of the rendering element layer in the GPU will not trigger redrawing. So try to use  transform: translate()  instead of left and top for animation.

Guess you like

Origin blog.csdn.net/qq_48113035/article/details/123285076