[] Introduced to redraw performance optimization and reflux (Repaint & Reflow), as well as how to optimize

Foreword

Reflow (Reflow) and redraw (Repaint) can be said to be two words every web developers are often heard, I am no exception, but I had not been very clear that this two-step what to do specific things. And very embarrassing performance optimization is often mentioned, we can say reducing reflux and redraw can improve page performance, of course, but a thorough ask what way? Might not say a concrete manifestation, so tidy up knowledge in this regard ↓

First, from the process of rendering browser

Here Insert Picture Description
From the above chart, we can see that the browser rendering process is as follows:

  1. Parsing HTML, DOM tree is generated, parsed CSS, generate CSSOM tree
  2. The DOM tree and tree CSSOM binding generates the render tree (Render Tree)
  3. Layout (reflux): based on the generated rendering tree reflux (Layout), to give the node geometry information (position, size)
  4. Painting (redraw): The geometry and rendering tree refluxed to obtain absolute pixel node
  5. Display (show): the pixels sent to the GPU, displayed on the page. (This step is in fact there are a lot of content, such as GPU will synthesize multiple layers combined into a single layer, and to show on the page. And css3 hardware acceleration principle is new synthetic layer, and we will not detail here)

The rendering process seems simple, let's specific knowledge at every step of specifically what to do.

Second, generate the render tree

Here Insert Picture Description
To construct the rendering tree browser mainly completed the following work:

  1. Start from the root node of the DOM tree traversal of each node is visible.
  2. For each node visible in the tree to find the corresponding rules CSSOM, and apply them.
  3. The visibility of each node and its corresponding pattern, the combination generating render tree.

The first step, since when it comes to traverse the visible nodes, then we must first know what nodes are not visible. Invisible nodes include:

  • Some will not render output node, such as <script>, <meta>, <link>and so on.
  • Some were hidden node through css. Such as display: none. Note that with the visibility and opacity hidden nodes, or will appear in the render tree. Only display: none of the nodes will not appear in the render tree.

From the above example is concerned, we can see that span style tags have a display: none, so it does not ultimately rendering tree.

Note: The render tree contains only the visible nodes

Reflow (Reflow)

Earlier we render tree by constructing, we will seen DOM node and its corresponding pattern combination, but we need to calculate their exact position within the apparatus and the size of the viewport (the viewport), and this phase is calculated reflux.

In order to clarify the exact size and position of each object on the site, the browser from rendering root of the tree begin to traverse, we may be expressed to the following example:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Critial Path: Hello world!</title>
  </head>
  <body>
    <div style="width: 50%">
      <div style="width: 50%">Hello world!</div>
    </div>
  </body>
</html>

We can see that the display size is provided to the first node is a div viewport width of 50%, 50% second div dimensioned parent node. In this reflow stage, we need to Viewport specific width, which is converted to actual pixel values. (As shown below)

Redraw (Repaint)

Ultimately, we construct by rendering trees and reflux stage, we know which nodes are visible, and each node node visible and concrete style of geometric information (location, size), then we can render tree are converted to actual pixels on the screen, this stage is called redraw node.

Now that you know the rendering process browser, the next we are going to explore, when it will redraw the reflux occurs.

Third, the reflux occurs when redrawing

We know that the front reflux This phase is the location and geometric information of compute nodes, and then when the page layout geometry information changes, you need to reflux. For example, the following:

  • Add or remove visible DOM element
  • Position of the element changes
  • Size of the element is changed (including margins, the frame, frame size, height, and width)
  • Content changes, such as changes in text or image is replaced by a different sized images
  • Page rendering start time (which certainly can not be avoided)
  • Browser window size change (because the reflux position and size are calculated according to the element size of the viewport)

According to the scope and extent of change, rendering tree or large or small parts need to be recalculated, some changes will trigger the entire page rearrangement , for example, when the scroll bar appears, or modify the root

Note: reflux will trigger the redraw, and will not necessarily be redrawn reflux

Fourth, the browser's rendering mechanism, and the animation process optimization mechanism

Browser rendering mechanism
  • Browser using flow layout model (Flow Based Layout)
  • The browser will parse HTML into DOM, CSS parsed into the CSSOM, DOM and CSSOM merger gave rise to render tree (Render Tree)
  • With RenderTree, we know the style for all nodes, and then calculate their size and position on the page, and finally draw the node onto the page
  • Since the browser uses flow layout, calculation of the Render Tree usually need only to traverse once to complete, with the exception of table and interior elements, they may be necessary to calculate the time it usually takes three times the same element, which is to avoid one of the reasons why the use table layout
Browser Optimization Mechanism

Most modern browsers are updated through a batch queue mechanism to the layout, the browser will modify the operation in a queue, at least one browser refresh (ie 16.6ms) will empty the queue, but when you get time layout information, queue there may affect these properties or methods of operation return value, even if not, the browser will be forced to empty the queue, triggering reflux and redrawn to ensure that returns the correct value

Or a method including the following attributes:

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

The above properties and methods need to return the most recent layout information, the browser has to empty the queue, triggering reflux redrawn to return the correct value. Therefore, we modify the style of the time, best to avoid the use of the properties listed above, they will refresh render queue . If you want to use them, the best value cached

Browsers handle the animation process

Here Insert Picture Description

  • The browser will parse HTML into DOM, CSS parsed into the CSSOM, DOM and CSSOM merger gave rise to render tree (Render Tree)
  • Segmentation Layer: Browser The z-index, and layers from the original dom dom deconstruction stratified
  • Computed Style: decomposition layer is completed, all layers will be batch style computing. Here is the CPU to calculate some property, some property is to GPU computing
  • reflow -> relayout -> paint set up -> repaint: This series of process steps is actually happening from the back to the page redraw, which is why reflux inevitably lead to redraw, and the reason is not necessarily to be redrawn reflux
  • GPU: redrawn "canvas" to the GPU to handle
  • Combined layout: browser layout combinations, then appeared page

Fifth, how to reduce reflux and redraw

CSS

  • Use transform an alternative top
  • Use visibility replace the display: none, because the former would lead to redraw, which will lead to reflux (changing the layout)
  • Avoid using table layout, may be small, a small change will result in re-layout of the entire table
  • As far as possible in the DOM tree change very end of class, reflux is inevitable, but it can reduce its impact. In the DOM tree as the endmost class changes, can limit the scope of the reflux, as few nodes as its impact
  • The multilayer avoid setting inline styles, CSS selectors match lookup from right to left, to avoid excessive node hierarchy
<div>
  <a> <span></span> </a>
</div>
<style>
  span {
    color: red;
  }
  div > a > span {
    color: red;
  }
</style>

For the first set style way, the browser just need to find all the span tags page and then set the color, but the style is set for the second way, the browser first need to find all the span tags, then found a label on the span tag, and finally go to find the div tag, and then to span labels meet these conditions set the color, this recursive process is very complicated. So we should try to avoid writing too specific CSS selectors, and as little as possible for HTML is also adding meaningless tags, flat hierarchy guarantee

  • The animation effect to the position attribute on the element of absolute or fixed, to avoid affecting the layout of other elements, so that only a redraw, instead of being returned, at the same time, control the animation speed can be selected requestAnimationFrame, see explore requestAnimationFrame
  • Avoid using CSS expressions, may cause reflux
  • Frequently redrawn or reflux node is set for a layer, the layer can prevent the rendering behavior of the node affect other nodes, for example, will-change, video, iframe and other labels, the browser will automatically become the node layer
  • CSS3 hardware acceleration (GPU acceleration), using css3 hardware acceleration, allowing transform, opacity, filters these animations do not cause reflux redrawn. But for the other attributes of animation, such as background-color them, or it will cause reflux redrawn, but it still can improve the performance of these animations

We can look at a demo example . I use chrome by the Performance capture animation for some time to redraw the case of reflux, actual results in the following figure
Here Insert Picture Description
we can see from the figure, at the time of animation, there are Layout (reflux), since there is reflux of course there will be painting ( redraw). But according to the theory, it is no use to reflux and redrawn, as to which I reviewed what other information is also not related to the instructions in this regard, if there is I'll update up, perhaps I may be also test question reasons for it, it will not tangle we need to know css3 hardware acceleration can enhance the performance of a page -

Emphasis

  • Css3 using hardware acceleration, allowing transform, opacity, filters these animations do not cause reflux redraw
  • For other property of animation, such as background-color them, or will cause redraw, but does not cause reflux, but before it can still enhance performance

css3 hardware acceleration shortcomings

Of course, css3 hardware acceleration still have a pit:

  • If you use too many elements css3 hardware acceleration will lead to large memory footprint, there will be a performance problem.
  • In GPU rendering font anti-aliasing will result invalid. This is because different GPU and CPU algorithms. So if you are not the end of the animation off hardware acceleration, it will have fuzzy fonts.

JavaScript

  • Avoid frequent operation pattern, the best one-time override the style property, or the style list is defined as a class and a one-time change the class attribute

Code shows:

const el = document.getElementById('test');
el.style.padding = '5px';
el.style.borderLeft = '1px';
el.style.borderRight = '2px';

There are three style property is modified, it will affect the geometry of each element, to cause reflux. Of course, most modern browsers it is optimized, therefore, will only trigger a rearrangement. But if the older version of the browser or when the above code is executed, there are other code to access the layout information (in the above layout information will trigger reflux), it will lead three times rearrangement, so we can then merge all changes order processing, for example, we should be changed ↓

const el = document.getElementById('test');
el.style.cssText += 'border-left: 1px; border-right: 2px; padding: 5px;';
  • Avoid frequent operation DOM, create a documentFragment, apply all DOM operations on it, then add it to the final document

Code shows:

function appendDataToElement(appendToElement, data) {
    let li;
    for (let i = 0; i < data.length; i++) {
    	li = document.createElement('li');
        li.textContent = 'text';
        appendToElement.appendChild(li);
    }
}

const ul = document.getElementById('list');
appendDataToElement(ul, data);

Use document fragment (document fragment) Construction of a subtree of the DOM outside of the current, and then copies it back to the document, it should be changed ↓

const ul = document.getElementById('list');
const fragment = document.createDocumentFragment();
appendDataToElement(fragment, data);
ul.appendChild(fragment);
  • Avoid frequent cause reflux read / redraw the property, if you do need to use many times, it is cached by a variable

Code shows:

function initBox() {
    for (let i = 0; i < paragraphs.length; i++) {
        paragraphs[i].style.width = box.offsetWidth + 'px';
    }
}

It looks like no problem, but in fact can cause significant performance issues. In each cycle time, we have a read attribute value offsetWidth box, and then use it to update the tag width attribute p. This leads to a cycle every time the browser must first make the last loop style update to take effect, in order to respond to the style of this cycle of read operations. Each cycle will force the browser to refresh the queue. We can be optimized for ↓

const width = box.offsetWidth;
function initBox() {
    for (let i = 0; i < paragraphs.length; i++) {
        paragraphs[i].style.width = width + 'px';
    }
}
  • The use of elements with complex animations absolute positioning, so that it flows out of the document, otherwise it will cause the parent element and subsequent elements frequent reflux

In this complex animation effects, since often the cause reflux redrawn, so we can use absolute positioning, let it flow out of the document. Otherwise it will cause the parent element and subsequent elements frequent reflux, you can see the code page → Demo Examples

After opening this example, we can open the console will output the current number of frames (although allowed) on the console. But we had never found the number of frames to 60.

We can also refer Performance properties of flame chart, we can see that when the animation is not determined location, you can see from the figure Rendering (rendering calculations, including reflux) and Painting (redraw) has been recorded at the peak of performance stage, can also be seen from the chart ring, the reflux (Layout, you can enlarge each Rendering can see) has been engaged in the calculation of the
Here Insert Picture Description
fs frames when we click on the button, the animation is to flow out of the document, on the console 60 can be stabilized again, and we go crawl animation performance , at this time we can see that the ratio Rendering Painting and share a few, visible animation set to absolute positioning from the document flow, can greatly optimize the performance of our page!
Here Insert Picture Description

Six, finishing

Finally tidy css style property in which can lead to reflux and redraw, and when to turn on GPU acceleration

Trigger reflux

1) box model related attributes:

  • width * height
  • offset * client * scroll
  • padding * margin
  • border * border-width
  • min-height(width) * max-height(width)
  • display

2) positioning and floating

  • top * bottom * left * right
  • position
  • float
  • clear

3) change the internal structure of the text node

  • text-align * line-height * vertical-align
  • overflow * overflow-y * overflow-x
  • font-family * font-size * font-weight
  • white-space
Trigger redraw
  • border-style * border-radius
  • visibility * text-decoration
  • color * background * background-image * background-position * background-repeat * background-size
  • outline-color * outline * outline-style * outline-width
  • box-shadow
GPU acceleration trigger

concept:

Create a new layer, change the property directly handled by the GPU, speed up processing. Make some changes attributes can skip relayout (Reflux), reducing the browser animation runtime needs to be done

Drawback: GPU use can increase memory consumption, but also affect the anti-aliasing fonts, causing the text during the animation looks a little fuzzy

With chrome browser for example, the following conditions are met, it will create a separate layer:

1) transform (3d conversion)

2) video tag

3) plug-in hybrid (such as Flash)

4) isolation == isolate

5)opacity < 1

6)filter != normal

! 7) z-index = auto || 0 + parent element display: flex | inline-flex

8)mix-blend-mode != normal

9)position == fixed || absolute

10)-webkit-overflow-scrolling == touch

11) will-change: Specifies the new layer of the element may be formed

7 Conclusion

This paper stresses the rendering process browser, browser optimization mechanism and how to reduce or even avoid reflux and redraw, and finally need to thank God that several big part of this dedication ↓

Reference article:
Do you really understand reflux and redraw it
render tree construction, layout and drawing
reflow reflow repaint redraw hardware acceleration

Published 134 original articles · won praise 80 · views 30000 +

Guess you like

Origin blog.csdn.net/Umbrella_Um/article/details/100744981