To learn CSS animation, you need to understand the principles of browser rendering and animation performance optimization related knowledge, so as to write a smooth animation effect.

Browser processes and threads

Processes and threads

  1. A process is the smallest unit of CPU resource allocation. It is independent of each other and has one or more threads in the process
  2. Threads are the smallest unit of CPU scheduling. Threads collaborate with each other and share a memory space

Browsers are multi-process

Browsers are multi-process, including:

  • Browser process: the main process of the Browser (responsible for coordination and control), there is only one

    • Responsible for browser interface display and user interaction. Forward, backward, etc
    • Responsible for page management, creating and destroying other processes
    • Draw the Bitmap in memory obtained by the Renderer process onto the user interface using the GPU
    • Network resource management, download, etc
  • Third-party plug-in process: Each type of plug-in corresponds to one process, which is created only when the plug-in is used
  • GPU process: a maximum of one. It is used for 3D drawing
  • The browser Renderer (the browser kernel) (the Renderer process, which is multi-threaded internally) by default has one Renderer for each TAB opened, independent of each other. Main functions: page rendering, script execution, event processing and so on

Note: browsers have their own optimization mechanisms, such as opening multiple blank tabs that can be combined into a single process, so one TAB for one process is not absolute.

Rendering process

For the front end, the most important thing is the rendering process. The rendering process is multi-threaded internally, mainly including:

  • Js engine thread

    It is used to execute JS scripts. Js is a single thread mechanism, all tasks have to be run in the main thread in sequence. When the main thread is idle, it will process the task queue like timer.

  • GUI rendering thread

    • Responsible for rendering browser interfaces, parsing HTML, CSS, building DOM trees and RenderObject trees, layout and drawing, etc
    • This thread executes when the interface needs to be repainted or when some operation causes reflow
    • GUI rendering thread and JS engine thread are mutually exclusive, GUI thread will be suspended when JS engine is executing, GUI updates will be stored in a queue until JS engine is idle and executed immediately, so JS will block page rendering
  • Timer thread The thread where setTimeOut and setInterval reside controls the timing of the timer. After the timer is completed, put the tasks in the timer into the task queue and wait for the js main thread to be idle

  • Asynchronous Network request thread The thread of the HTTP request that asynchronously processes the network request. If the request has a callback function, it puts the callback function into the main thread to execute.

Rendering process

  1. The Brower process receives the user request, obtains the network resource first, and then invokes the renderer process to render
  2. The renderer receives the message and interprets it briefly, handing it over to the renderer thread,
    • The render thread receives the request, loads the page, and renders the page, which may require the Browser process to fetch resources and the GPU process to help render
    • There may be JS threads manipulating the DOM (this may cause backflow and redrawing)
    • Finally, the Render process passes the result to the Browser process
  3. The Browser process draws the rendering results to the screen

From a rendering perspective, the rendering process can also be divided into main and composite threads, as shown below:

  1. Creating a Document Object Model (DOM) using HTML
  2. Creating a CSS Object Model with CSS (CSSOM)
  3. Execute Scripts based on DOM and CSSOM
  4. Combine DOM and CSSOM to form a Render Tree
  5. Use render tree Layout for all elements
  6. The Brower process controls the interaction between the renderer process and the GPU process for all elements.

Layer synthesis (composite)

Let’s start with a picture:

  • Chrome has two different rendering paths: the hardware-accelerated path and the old software path
  • Chrome has different types of layers: RenderLayer(which is responsible for the DOM subtree) and GraphicsLayer(which is responsible for the RenderLayer subtree). Only GraphicsLayer is uploaded to the GPU as a texture
  • What is texture? Think of it as a bitmap image moving from main memory (such as RAM) to image memory (such as VRAM in the GPU)
  • Chrome uses textures to get large chunks of page content from the GPU. It is easy to match positions and transformations by applying textures to a very simple rectangular mesh. It is time-consuming for GPU to load bitmap images, but it is very easy to process fast movement and deformation

Repaint and Rearrange/reflow


When we modify a page style, if there is no layout change, only a style change, such as a font color change, will cause the page to be redrawn


When the layout of the page changes, such as width and margin, it will cause rearrangement. Rearrangement must redraw, redrawing does not necessarily rearrange. So rearrangement is expensive.

Composite layer

The concept of composite was mentioned in the browser rendering process. In the DOM tree, each node corresponds to a LayoutObject. When their LayoutObject is in the same coordinate space, a RenderLayers will be formed, that is, the rendering layer. RenderLayers ensures that the page elements are composable in the correct order.

Composite layers occur when there are multiple rendering layers on a page with different coordinate Spaces, where multiple rendering layers share a GraphicsLayer parent and properly handle the display of transparent and overlapping elements.

Some particular render Layers are thought of as Compositing Layers, which have separate GraphicsLayer

Each GraphicsLayer has a GraphicsContext, and GraphicsContext is responsible for outputting bitmaps of this layer. Bitmaps are stored in shared memory and uploaded to GPU as textures. Finally, THE GPU will synthesize multiple bitmaps and display them on the screen

Advantages of synthetic layer

  • The bitmap of the synthesis layer is synthesized by the GPU, which is faster than the CPU
  • When repaint is required, only the composite layer is repainted, not the normal layer
  • Layout and Paint are not triggered for transform and opacity properties

How to ascend to the synthesis layer

  • CSS3D properties or CSS perspective effects such as transformZ(0)
  • Will-change is set to opacity, transform, top, left, bottom, and right (top, left, etc., should be set with clear location properties, such as relative etc.) (best way to improve the composition layer)
  • Use transition or animation on opacity or Transform
  • Contains RenderObject nodes corresponding to the video node
  • Contains RenderObject nodes using Canvas 2D or 3D (WebGL) technology
  • Uses hardware-accelerated CSS Filters technology
  • Use clipping or reflection properties, and their descendants contain compositing layers
  • There is a sibling node whose Z coordinates are smaller than its own, and the sibling node is a composition layer

Chrome Console looks at the rendering effect

Viewing hierarchy

Chrome -> Console -> More Tools -> Layers

#box1 {
    position: absolute;
    top: 50px;
    left: 0;
    width: 100px;
    height: 100px;
    background-color: pink;
#box2 {position: absolute; top: 200px; left: 0; width: 100px; height: 100px; background: yellowgreen; will-change: left; / /!!!!! Promote to composition layer} <div id="box1"></div>
<div id="box2"></div>
Copy the code

You can see in the console that there are two layers

Drawing process

Select the first and second ones. During animation, the repaint part will be marked green and the Rendering layer will have a pink border.

// css
#box1 {
    width: 100px;
    height: 100px;
    background: yellowgreen;
    transition: transform 5s 0s ease-out;

#box2 {
    position: absolute;
    top: 200px;
    left: 0;
    width: 100px;
    height: 100px;
    background-color: pink;
    transition: left 5s 0s ease-out;

// html
<div id="box1"></div>
<div id="box2"></div>

// js
document.querySelector('#box1').style.transform = 'translateX(100px)'
document.querySelector('#box2').style.left = '100px'
Copy the code

During the animation process, the animation controlling the left property will recalculate the bitmap of the rendering layer every time the left moves 1px, which will keep redrawing, resulting in the page stalling; Control the animation of transform, which will automatically promote elements to composite layers. The redrawing of the composite layer will not affect other layers. Meanwhile, the transform property will not cause layout and paint.

How to Optimize performance

  • Avoid frequent DOM operations directly on the document. If necessary, off-document can be used. Specific methods include but not all of the following:

    (1) Delete the element from the document, and then put it back in its original position. (2) Set the display element to “None”, and then set display to its original value. (3) If you need to create multiple DOM nodes, You can use the DocumentFragment to create a document once and for all

  • Centralized modification style

    (1) Modify the attributes on the element style as little as possible

    (2) Try to modify the style by modifying the className

    (3) Set the style through the cssText property

  • Cache Layout property values

    The browser does some low-level optimization for style changes. Instead of making style changes one by one, the browser maintains a queue of rendering tasks that the browser executes in batches as needed. In addition to the regular scheduling maintained by the browser itself, some operations in the script will cause the browser to execute the rendering task immediately, such as reading the Layout property of the element, such as offsetTop, scrollTop, etc.

    Non-reference values (numeric values) of a Layout property can be stored in a local variable for each access and then used to avoid browser rendering each time the property is read.

  • Since transform and opacity animation can be promoted to the compositing layer without causing layout or paint, try to use these two properties for animation. If the effect cannot be achieved, you can force the element to be promoted to the compositing layer. Use GPU acceleration.