1
头图
In daily development, by using css properties, when doing some dynamic effects and animations, you will find that there is a freeze on the page;
It is especially obvious on low-end Android machines, so you need to know browser rendering and optimization methods

Browser rendering process

image.png
image.png

  • Building the DOM tree: The browser parses the HTML into a tree-structured DOM tree. Generally speaking, this process occurs when the page is first loaded, or when the page JavaScript modifies the node structure.
  • Build a rendering tree: The browser parses the CSS into a tree-structured CSSOM tree, and then merges it with the DOM tree into a rendering tree.
  • Layout: The browser calculates the position of each node on the screen according to the nodes embodied in the rendering tree, the CSS definitions of each node, and their affiliation. The layout of elements in a web page is relative. Changes in the position and size of elements on the page often lead to linkage of other nodes, and the layout needs to be recalculated. The layout process at this time is generally called reflow/reflow .
  • Paint: Traverse the rendering tree and call the paint() method of the renderer to draw the node content on the screen, which is essentially a process of pixel filling. This process also occurs in partial repaints of the screen caused by reflows or some CSS changes that do not affect the layout. At this time, it is called repainting (Repaint) . In fact, the drawing process is done on multiple layers, which we call the RenderLayer .
  • Rendering layer composition (Composite): Multiple rendered rendering layers are combined in an appropriate overlapping order, and then a bitmap is generated, which is finally displayed on the screen through the graphics card.

The above are the basic steps of browser rendering, briefly described:

 DOM tree + CSS tree  == Render tree  ==>   Layout tree  ==>  PaintLayer => Composite
                                           PaintLayer => Composite

As long as the elements on the page change, some of the above steps will be repeated and completed within one frame (16.77ms);
By setting the css style and doing animation, the rendering cannot be completed in one frame, or even if it is too late to render, it will freeze;
Some of the rendering is stuck, which is related to the rendering layer composition (Composite).

Composite

What is render layer compositing

Each node in the DOM tree corresponds to a rendering object (RenderObject). When their rendering objects are in the same coordinate space (z-axis space), a RenderLayers is formed , that is, a rendering layer. The rendering layer will ensure that the page elements are stacked in the correct order, and this is where the layer composition occurs to correctly handle the display of transparent elements and overlapping elements. This step is called "stacking context"
This model is similar to Photoshop's layer model. In Photoshop, each design element is an independent layer, and multiple layers are superimposed on the z-axis space in an appropriate order, and finally constitute a complete design drawing.
This process is especially important for pages with overlapping elements, because if the layers are merged in the wrong order, the elements will display abnormally.

image.png

RenderObject

A DOM node corresponds to a rendering object, and the rendering object still maintains the tree structure of the DOM tree.

RenderLayer

This is the first layer model built during browser rendering . Rendering objects in the same coordinate space (z-axis space) will be merged into the same rendering layer . Therefore, according to the stacking context, rendering objects in different coordinate spaces Multiple render layers will be formed to reflect their cascading relationship.
Therefore, a RenderObject that satisfies the conditions for forming a stacking context will definitely create a new rendering layer for it. Of course, there are other special cases, creating a new rendering layer for some special RenderObjects, such as elements with overflow != visible. Depending on the reason for creating a RenderLayer, it can be divided into three common categories:

  • NormalPaintLayer
  • root element (HTML)
  • Have explicit positioning attributes (relative, fixed, sticky, absolute)
  • transparent (opacity less than 1)
  • Has CSS filters (fliter)
  • Has CSS mask property
  • Has CSS mix-blend-mode property (not normal)
  • Has CSS transform property (not none)
  • The backface-visibility property is hidden
  • Has CSS reflection property
  • Has the CSS column-count property (not auto) or has the CSS column-width property (not auto)
  • There are currently applied animations for opacity, transform, fliter, background-filter
  • OverflowClipPaintLayer
  • overflow is not visible
  • NoPaintLayer
  • A PaintLayer that doesn't need paint, like an empty div with no visual properties (background, color, shadow, etc.).

A RenderObject that meets the above conditions will have an independent rendering layer , while other RenderObjects share one with its first parent element that has a rendering layer.

GraphicsLayer

Rendering layer, shared with its first parent with a GraphicsLayer.
Each GraphicsLayer has a GraphicsContext, and the GraphicsContext is responsible for outputting the bitmap of the layer. The bitmap is stored in shared memory and uploaded to the GPU as a texture. Finally, the GPU synthesizes multiple bitmaps and then draws them to the screen. , at this point, our page is also displayed on the screen.

CompositingLayer

Rendering layers that meet certain special conditions will be automatically promoted to composite layers by the browser. The composition layer has a separate GraphicsLayer,
What special conditions can a rendering layer meet before it can be promoted to a composite layer? Here are some common cases:

  • 3D transforms: translate3d, translateZ, etc.
  • Elements such as video, canvas, iframe, etc.
  • Opacity animation transition via Element.animate()
  • Opacity animation transitions via СSS animations
  • position: fixed
  • Has the will-change property
  • Apply animation or transition to opacity, transform, fliter, backgroundfilter

Common and practical **transforms:translate3d、translateZ ** to form a composite layer, which has no effect on the original layout

Example

image.png
image.png

Other synthetic situations

Implicit synthesis

In addition, in the composite stage of the browser, there is also an implicit composition, and some rendering layers will be promoted to composite layers by default in some specific scenarios. In fact, the elements of the div overlap each other
image.png
As shown in the figure above: position-1 is used to generate a composite layer, and the following elements will overlap each other, in order to display the stacking context correctly; the latter elements are directly and implicitly synthesized;

Laminate compression

As shown above, there is no

Synthetic explosion

Through the study of the above figure, it is easy to generate some synthetic layers that are not within the expected range. When these synthetic layers that do not meet the expectations reach a certain magnitude, they will become layer explosions.
It is necessary to check whether there is overlap, and whether the stacking order can be adjusted by z-index

optimization

advantage

  • The bitmap of the composite layer will be composited by the GPU, which is much faster than the CPU processing;
  • When repaint is required, only repaint itself is needed, and other layers will not be affected;
  • After the element is promoted to a composite layer, transform and opacity will not trigger repaint. If it is not a composite layer, it will still trigger repaint. (Only css animation can be used, js will still be rearranged and redrawn to control) Use transform or opacity to achieve animation effect

Update element geometry (reflow occurs)
image.png
The browser will trigger a rearrangement, a series of sub-phases after parsing, this process is called rearrangement . Undoubtedly, rearranging requires updating the complete rendering pipeline, so the overhead is also the largest
Situations that trigger rearrangements

  • The page is rendered for the first time;
  • The browser window size changes;
  • The content of the element changes;
  • The size or position of the element changes;
  • The font size of the element changes;
  • activate CSS pseudo-classes;
  • Query certain properties or call certain methods;

    • offsetTop, offsetLeft, offsetWidth, offsetHeight
    • scrollTop, scrollLeft, scrollWidth, scrollHeight
    • clientTop, clientLeft, clientWidth, clientHeight
    • width, height
    • getComputedStyle()
    • getBoundingClientRect()
    • Add or remove visible DOM elements.

Update element drawing properties (redraw occurs)
image.png
If the background color of the element is modified, the layout phase will not be executed, because there is no change in the geometric position, so it directly enters the drawing phase, and then executes a series of subsequent sub-phases. This process is called redrawing. Compared with the rearrangement operation, redrawing eliminates the layout and layering stages, so the execution efficiency will be higher than that of the rearrangement operation .
A situation that triggers a repaint

  • rearrange
  • visibility: visible <=> hidden
  • color change
  • Other geometric variations...

direct synthesis stage
image.png
We use CSS transforms to achieve animation effects, which avoid the reflow and repaint phases and perform composite animation operations directly on the non-main thread. This kind of efficiency is the highest, because it is synthesized on a non-main thread, it does not occupy the resources of the main thread , and also avoids the two sub-stages of layout and drawing, so compared to redrawing and rearranging, synthesis can greatly improve drawing. efficiency.
shortcoming

  • Drawn layers must be transferred to the GPU, and when the number and size of these layers reaches a certain magnitude, the transfer can be very slow , which in turn can cause flickering on some low-end and mid-range devices;
  • Implicit compositing is prone to excessive compositing layers, each compositing layer takes up additional memory , and memory is a precious resource on mobile devices. Excessive use of memory can cause browser crashes, making performance optimizations justified

    Other optimizations

    css

  • Use transform instead of top
  • Replace display: none with visibility, because the former will only cause a redraw, the latter will cause a reflow (changes the layout
  • Avoid using table layouts, as a small change may cause the entire table to be re-layout.
  • Change classes as far as possible at the very end of the DOM tree, reflow is unavoidable, but its impact can be reduced. Changing the class as far as possible at the very end of the DOM tree limits the scope of the reflow to affect as few nodes as possible.
  • Avoid setting multiple layers of inline styles. CSS selectors are matched and searched from right to left to avoid too many node levels.
  • Apply the animation effect to the element whose position attribute is absolute or fixed to avoid affecting the layout of other elements. This is just a redraw, not a reflow. At the same time, you can choose requestAnimationFrame to control the animation speed. For details, please see requestAnimationFrame .
  • Avoid using CSS expressions, which may cause reflow.
  • Set a node that is frequently redrawn or reflowed as a layer. The layer can prevent the rendering behavior of the node from affecting other nodes, such as will-change, video, iframe and other tags, and the browser will automatically turn the node into a layer.

    js:

  • To avoid frequent manipulation of styles , it is better to rewrite the style attribute at one time , or define the style list as a class and change the class attribute at one time.
  • To avoid frequent manipulation of the DOM, create a documentFragment , apply all DOM manipulations on it, and finally add it to the document.
  • Avoid frequently reading properties that will cause reflow/redraw , and if you really need to use them multiple times, cache them in a variable.
  • Use absolute positioning for elements with complex animations to keep them out of the flow of the document, otherwise it will cause frequent reflows of the parent and subsequent elements.

    Summarize

    When doing animation, use the csstransforms attribute as much as possible to do animation, it skips the Layout and Paint stages and directly enters the rendering, so it will improve some performance, and at the same time check the space position to see if the composition layer is improved; also pay attention to the elements Whether to overlap to prevent the explosion of the composite layer; this can at least ensure that there is no problem in performance as far as possible in terms of css.
    For the rest, please check other optimization methods

sample code

overlapping

 <style>
 .ball-running,.ball-running1 {
      width: 100px;
      height: 100px;
      animation: run-around 4s linear alternate 100;
      background: red;
      position: absolute;
      border-radius: 50%;
    }
    @keyframes run-around {
      0% {
        top: 0;
        left: 0;
      }
      25% {
        top: 0;
        left: 200px;
      }
      50% {
        top: 200px;
        left: 200px;
      }
      75% {
        top: 200px;
        left: 0;
      }
    }
    .position-1,.position-2,.position-3,.position-4 {
      position: absolute;
      width: 100px;
      height: 100px;
      background-color: red;
      border: #1b1b1b 1px solid;
    }
    .position-1 {
      transform: translateZ(10px);
    }
    .position-2 {
      top: 90px;
      left: 90px;
     // transform: translateZ(10px);
    }
    .position-3 {
      top: 180px;
      left: 180px;
    }
    .position-4 {
      top: 270px;
      left: 270px;
    }
    .parent-1 {
      //width: 100px;
      //height: 200px;
      background: #5b3a13;
      //overflow: auto;
      //transform: translateZ(10px);
    }
    .position-5 {

    }
<style/>    
<div class="parent-1">
      <div class="position-1">
        1
      </div>
      <div class="position-2">
        2
      </div>
      <div class="position-3">
        3
      </div>
      <div class="position-4">
        4
      </div>
    </div>

animation

 <style>
.ball-running,.ball-running1 {
      width: 100px;
      height: 100px;
    //  animation: run-around2 4s linear alternate 100;
      background: red;
      position: absolute;
      border-radius: 50%;
    }
    @keyframes run-around {
      0% {
        top: 0;
        left: 0;
      }
      25% {
        top: 0;
        left: 200px;
      }
      50% {
        top: 200px;
        left: 200px;
      }
      75% {
        top: 200px;
        left: 0;
      }
    }





    //.ball-running {
    //  width: 100px;
    //  height: 100px;
    //  animation: run-around 2s linear alternate 100;
    //  background: red;
    //  border-radius: 50%;
    //}
    //@keyframes run-around {
    //  0% {
    //    transform: translate(0, 0);
    //  }
    //  25% {
    //    transform: translate(200px, 0);
    //  }
    //  50% {
    //    transform: translate(200px, 200px);
    //  }
    //  75% {
    //    transform: translate(0, 200px);
    //  }
    //}

</style>
<div class="ball-running"></div>

refer to:

The performance difference between transform and left changing position
GPU Accelerated Compositing in Chrome
Browser layer composition and page rendering optimization
Browser rendering process and page optimization
Wireless performance optimization: Composite
browser rendering process
rendering process
Stick to Compositor-Only Properties and Manage Layer Count


散一群逗逼
554 声望508 粉丝

做一位有逼格的前端工程师