preface

In order to better understand browser performance optimization, this article will analyze the key points of performance optimization step by step from the browser multi-process architecture and browser rendering process

Multi-process architecture for browsers

Processes and threads

A process is similar to a factory that has separate resources and is independent of each other

Threads are similar to workers in a factory, where multiple workers collaborate on tasks and share space with each other

Simple understanding:

  • A process is the smallest unit of CPU resources, and the system allocates memory to it
  • Threads are the smallest unit of CPU scheduling and can have one or more threads in a process
  • Different processes can also communicate with each other but at a higher cost

Browser multiprocess

Simple understanding:

  • Browsers are multi-process
  • The browser works because the system allocates CPU and memory resources to its processes
  • Basically, opening a Tab page creates a separate browser process

Note: The browser has its own optimization mechanism, the process of opening multiple TAB pages will be merged (for example, multiple blank pages merge).

Why browsers are multi-process (main reason)

Imagine that if the browser is single-threaded, the crash of a Tab page or plug-in script can affect the entire browser, so the browser is designed to be multi-process for stability

What major processes are included in the browser

  1. Browser process: The master process of the Browser
    • Responsible for browser interface display and user interaction
    • Responsible for the management of individual pages, create or destroy other processes
    • Draws a bitmap (bitmap) stored in memory by the browser renderer process onto the user interface
    • Network resource management, download, etc
  2. Third-party plug-in process: Each type of plug-in corresponds to one process, which is created only when the plug-in is used
  3. GPU process: a maximum of one GPU process can be used for 3D drawing
  4. Renderer process: This process is multi-threaded internally, one process per Tab page by default, does not affect * page rendering, script execution, event processing, etc

Refine the browser rendering process

Page rendering, JS execution, event loops, etc. are performed in this process, which contains multiple threads

  1. GUI rendering thread
    • This thread is responsible for rendering the page, parsing HTML into CSS, and building the DOM tree and generating the RenderObject tree
    • The thread executes when a single page needs to be redrawn or when some operation backflows
    • Note: The GUI rendering thread and JS thread are mutually exclusive to ensure that the page does not mess up due to DOM changes during rendering
  2. JS engine thread
    • It is the JS kernel, responsible for handling the JS scripting language (V8 engine)
    • Is there only one JS thread running on a Tab page (renderer process) at any one time
  3. Event trigger thread
    • It belongs to the browser for processing the triggered event and puts its callback function in the task queue. When the JS main execution stack is empty, the callback function in the task queue will be executed according to certain rules
  4. Timer trigger thread
    • Used to handle setTimeout or setInterval
  5. Asynchronous HTTP request threads
    • It is used to handle asynchronous HTTP requests that exist in the page and put the callback into the event queue, which is finally executed by the JS engine

Page building process

Browser processing

  • The browser starts a process to host the TAB page
  • The process contains
    • GUI rendering thread: Used to build and render the page after obtaining the HTML
    • JS engine threads: Used to process THE JS code in a page. Each browser process has one
    • Event handler thread: Used to handle callbacks generated by user-triggered events
    • HTTP processing thread: Used to process HTTP requests
    • Timer trigger thread: Used to process timers generated in the page and defer callbacks to the task queue when appropriate

Note: GUI thread and JS thread are mutually exclusive to ensure data and view unity

Build process (GUI rendering thread)

  1. The browser parses the HTML line by line and creates a DOM tree. DOM tree creation is a deep traversal process. The next sibling node of the current node will be built only after all the child nodes of the current node are built.
  2. If an external JS file is encountered and asynchronous execution is not set, download it immediately and execute it synchronously. If a CSS file is encountered, download it immediately and generate CSSOM
  3. Document. ReadyState =” Interaction “after HTML parsing is completed, the complete DOM tree is combined with CSSOM to generate the RenderTree.

Rendering process

  1. RenderTree consists of RenderObject, a rendering object corresponding to a DOM node, which contains node information and rendering context
  2. All rendering objects in the same coordinate space will be merged into a rendering layer. For the rendering object that forms a cascading context, a new rendering layer will be automatically created for it, and the rendering object will automatically be subordinate to the closest rendering layer of the parent element, which is the common way to generate a rendering layer
    • The root document
    • postion: relative/absolute/fixed/sticky
    • opacity < 1
    • The CSS fliter attribute exists
    • The CSS Transform property exists
  3. On the basis of the render layer satisfy certain conditions after the render layer will be promoted to synthesis (graphics layer), has a separate graphics context (equivalent to the separate rendering), the rest is not a synthetic rendering layer and the first with the father of the graphics context Shared a composite layer, the effect of the composite layer is usually change often
    • 3Dtransforms: translate3D/translateZ
    • video/canvas/iframe
    • CSS animation implementation of opacity animation conversion
    • position:fixed
    • will-change
    • Transition or animation is applied to opacity/transform/fliter
    • Using Clip or Reflection
    • Note: Upgrading the rendering layer to the compositing layer will have GPU acceleration effects, but can’t be abused
  4. Once you have the layers, the browser calculates where each layer is on the page (backflow) and invokes its drawing context to render, rendering the entire page

Implicit synthesis with layer explosion and layer compression

If one or more non-synthetic elements are stacked on top of the composite layer elements, these non-synthetic layer elements are promoted to the composite layer, resulting in implicit composition

  • Layer explosion refers to the phenomenon that too many composite layers occupy A large amount of GPU and memory resources, which leads to page stalling or flickering. The solution is to improve the z-index of the composite layer to avoid overlapping and eliminate implicit synthesis
  • Layer compression is the browser’s own optimization mechanism. It can compress the redundant stacked composite layers generated by implicit composition into a composite layer, thus greatly reducing the number of composite layers and reducing GPU and memory consumption

Advantages and disadvantages of layer composition rules

advantages

  • Bitmaps generated by layer synthesis will be individually processed by GPU, which is faster than CPU
  • Repainting is required only by repainting itself without affecting other layers
  • After an element is promoted to a composite layer, the change part of transform or opacity triggers redrawing

disadvantages

  • Too many composite layers cause high GPU usage and prone to page flickering
  • Implicit composition creates too many layers of composition and consumes too many resources

Optimize the way

  • The animation is implemented using transform
  • Reduce implicit compositing, animate nodes set to high Z-index
  • By reducing the size of the composite layer, you can use scale to save performance

Redraw and reflow

  • Redraw: The size and layout are not changed, only some styles are changed
  • Backflow: Changes in the size and layout of elements on the page (except composition layers)

Redraw does not necessarily reflux, reflux must redraw

An operation that causes backflow

  • Initial page rendering
  • Change the size of a font or element
  • Change the visible content of an element
  • Add and delete DOM elements
  • Fixed elements will always flow back when scrolling
  • Resize the window
  • Access offsetWidth or offsetHeight to destroy the Flush queue

Flush the queue

For performance optimizations, the browser maintains a flush queue that stores the contents of the flush queue and flushes them all at once after a certain period of time or when the queue reaches a certain length. However, when a developer accesses attributes such as offsetwidth, offsetheight, Width, height, etc., the browser will break the Flush queue in order to return the developer the exact value of that element, rendering the browser optimization ineffective

Page optimization performance approach

The code level

  • Try to use CSS3’s transfrom instead of the top left operation when changing the position of elements, because the transformation only affects the combination position of layers
  • Use opacity instead of visibility, as transparency does not trigger redrawing
    • Note: When the opacity changes, the GPU simply lowers the alpha value of the previously drawn texture to achieve the effect
  • Merge multiple class style changes into one (pre-define the changed class)
  • Use display: None to modify the DOM element offline
  • Use documentFragment documentFragment to collect backflow elements in a short time and add them to the page after a backflow (optimized for the same version of vue)
  • The animation implementation process uses Transfrom :tranleteZ(0) to elevate it to a composite layer by GPU rendering alone
  • Create a new layer for the animation element and increase its Z-index to reduce implicit composition
  • Reduce access to flush queues and try not to break browser optimizations
  • Monotonic color blocks can be used to optimize memory footprint using scale scaling in composition layer optimization
  • CSS above JS below triggers first paint in the browser and reduces the chance that synchronous code blocks rendering

Resource level

  • In addition to the first screen display, other resources (images, components, videos, etc.) are loaded lazily
  • The video contained in the first screen can be split and transmitted
  • Canvas or SVG can be used for drawing when monotonous images are too large for performance
  • To compress HTML, JS, and CSS resources, enable Gzip on the server
  • Use caching for static resources
  • Using CDN to shorten the distance between users and resources * Upgrading to HTTP2 enables resources to enjoy binary transport, header compression, and multiplexing