Front-end performance optimization-reduce redraw and reflow

When the page loads, the browser parses the obtained HTML code into a DOM tree. The DOM tree contains all HTML tags, including display: none hiding, and elements added dynamically with JS.
  The browser parses all styles (user-defined CSS and user agents) into a style structure
  DOM Tree and a combination of style structures to build a render tree. The render tree is similar to the DOM tree, but there is a big difference because the render tree can recognize style Each NODE in the render tree has its own style, and the render tree does not contain hidden nodes (such as display: none nodes, and head nodes), because these nodes will not be used for rendering and will not affect the rendering So it will not be included in the render tree. My own simple understanding is that after the DOM Tree and the CSS we wrote together, the render tree is rendered.

Backflow

When some or all of the render tree needs to be rebuilt due to changes in the size, layout, and hiding of elements, it is called reflow. When the page layout and geometric properties change, reflow is required.

Each page needs to be reflowed at least once, that is, when the page is loaded for the first time, reflow must occur at this time, because the render tree is to be constructed. During reflow, the browser will invalidate the affected part of the rendering tree and reconstruct this part of the rendering tree. After the reflow, the browser will redraw the affected part to the screen, which is called redrawing.

Redraw

When some elements in the render tree need to update attributes, these attributes only affect the appearance and style of the element, and will not affect the layout, such as background-color

The relationship between reflow and redraw

Reflow will definitely cause redraw, and redraw does not necessarily cause reflow.

Two ways to avoid redrawing and reflow

1. backflow

  • Box model related attributes will trigger re-layout and page reflow

width height padding margin display border-width border min-height min-weight

  • Positioning attributes and floats will also trigger re-layout

top right bottom left position float clear

  • Changing the internal text structure of the node will also trigger the center layout

Text-aligin over-flow-y font-wieght overflow font-family line-height vertical-align white-space font-size

2. Redraw

color border-style border-radius visivbility text-tecoration background background-image background-position background-repeat background-size outline-color ouline outline-style outline-width box-shadow

 


For example:
        you can see the video of iQiyi, you can see all the layers on this page in layers, and you can also see the layer information, such as why it should be used as a single layer: Compositing Reasons


When redrawing, paint flashing will mark the redrawn elements green, for example, the video has been redrawn while playing

The process of creating a new DOM

  1. Split into multiple layers after obtaining dom
  2. Calculate the style result for each layer node (Recalculate style-style recalculation)
  3. Generate graphics and positions for each node (Layout-reflow and re-layout)
  4. Fill each node into the layer bitmap (Paint Steup and Paing-redraw)
  5. The layer is uploaded to the GPU as a texture
  6. Combine multiple layers onto the page to generate the final screen image (Composite Layers-layer reorganization)

If the DOM elements that are frequently redrawn and reflowed are used as an independent layer, then the effects of redrawing and reflowing the DOM elements will only be in this layer.

How to turn dom elements into new independent layers

Conditions for creating layers in Chrome

  1. 3D or perspective transform css attributes (perspective transform)
  2. Use <video> node for accelerated video decoding
  3. Canvas node with 3D (WebGL) context or accelerated 2D context
  4. Mixed plugins such as flash
  5. Use CSS to animate your own opacity or use an animated webkit to transform the elements
  6. Elements with accelerated css filters
  7. The element has a descendant node that contains a compound layer (an element has a child element, which is in its own layer)
  8. The element has a sibling element with a lower z-index and containing a matching layer (in other words, the element is rendered on the composite layer)

Optimization point

1. Browser optimization mechanism

Modern browsers are very smart, because each reordering will cause additional computational consumption, so most browsers will optimize the reordering process by queueing modifications and batch execution. The browser puts the modification operation into the queue, and does not clear the queue until after a period of time or when the operation reaches a threshold. but! When you get the operation of layout information, it will force the queue to refresh, for example, when you access the following properties or use the following methods:

offsetTop、offsetLeft、offsetWidth、offsetHeight、scrollTop、scrollLeft、scrollWidth、scrollHeight、clientTop、clientLeft、clientWidth、clientHeight、getComputedStyle()getBoundingClientRect

The above attributes and methods need to return the latest layout information, so the browser has to clear the queue and trigger a reflow to return the correct value. Therefore, when we modify the style, it is best to avoid using the attributes listed above, they will refresh the rendering queue.

If we want to get and manipulate these values ​​frequently, we can cache these values ​​first.

2. Optimization

Because retrieving attribute values ​​triggers reflow, because reflow has a caching mechanism, when reading using attribute values, the buffer is forcibly refreshed, because to obtain real data, the buffer mechanism will be invalid

Layers cannot be abused because they will affect performance and consume a lot of time on layer composition

  1. Do not change the style of the child element through the parent. It is best to directly change the style of the child element. Changing the style of the child element should not affect the size and size of the parent element and the sibling element.
  2. Try to design element styles through class, avoid using style.
  3. For complex animation effects, use absolute positioning to make it separate from the document flow, otherwise it will cause a large amount of reflow of the parent element and subsequent elements.
  4. Another reason not to use table layout is that once an element in the table triggers reflow, it will cause all other elements in the table to reflow. In the case of suitable table, you can set table-layout to auto or fixed.
  5. Avoid setting multiple layers of inline styles.
  6. Use modified style cssText.
  7. Avoid using css attributes that trigger redraw and reflow
  8. Limit the scope of redraw and reflow to a separate layer
  9. Use translate instead of top
  10. Replace visibility with opacity
  11. Do not modify the DOM style one by one, pre-define the class, and then modify the DOM className
  12. Modify the dom offline, for example, first give the DOM to display: none (once Reflow), then you modify it 100 times, and then display it
  13. Do not put the attribute values ​​of DOM nodes in a loop as variables in the loop, such as offsetHeight, offsetWidth
  14. The choice of animation implementation speed, limiting the frequency, because it consumes cpu resources
  15. For animation new layer video canvas transform property
  16. Enable GPU acceleration, such as webGL when using position changes

Why not use top

Because top triggers reflow, but translate does not, give an example

Examples

1. Use top

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .text-box{
            position: absolute;
            left: 0;
            top: 0;
            width: 100px;
            height: 100px;
            background: red;
        }
    </style>
</head>
<body>
<div class="text-box">

</div>
<script>
    window.onload = () => {
        setTimeout(() => {
            let boxDomList = document.querySelectorAll('.text-box');
            boxDomList[0].style.top = '100px';
        }, 2000)
    }
</script>
</body>
</html>

It can be seen that in 2s, the top will become 100px

First stage: Reaclculate Style 68 μs

Second stage: Layout triggers the reflow process 25 μs

The third stage: Update Layer Tree 68 μs

Fourth stage: Paint repainting 23 μs

The fifth stage: Composite Layers image synthesis 0.11ms

Shared 68 + 25 + 68 + 23 + 110 = 294 μs

2. Use translate instead

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .text-box{
            /*position: absolute;*/
            /*left: 0;*/
            /*top: 0;*/
            transform: translateY(0);
            width: 100px;
            height: 100px;
            background: red;
        }
    </style>
</head>
<body>
<div class="text-box">

</div>
<script>
    window.onload = () => {
        setTimeout(() => {
            let boxDomList = document.querySelectorAll('.text-box');
            boxDomList[0].style.transform = 'translateY(100px)';
        }, 2000)
    }
</script>
</body>
</html>

No layout reflow

First stage: Reaclculate Style 80 μs

Second stage: Update Layer Tree 60 μs

The third stage: Composite Layers image synthesis 75 μs

Total time: 80 + 60 + 75 = 215 μs

Compared to the first time, it saves 79 μs , although not much, but if the layout is very complicated and there are many reflows, the page will get obvious benefits

Use scenario: page floating window

 

Published 5 original articles · Likes0 · Visits 118

Guess you like

Origin blog.csdn.net/forteenBrother/article/details/105616725