1

Inside look at modern web browser is a series of articles that introduces the principle of browser implementation. There are 4 articles in total. This intensive reading introduces the third article.

Overview

This article gives a macro introduction to what the renderer process does.

The html, css, and javascript content in the browser tab are basically processed by the main thread of the renderer process, except for some js codes that will be placed in the web worker or service worker, so the core work of the browser main thread is to parse the web three swordsmen and generate Interactive user interface.

Parsing stage

First of all, the main thread of the renderer process will parse the HTML text into DOM (Document Object Model). Only translating into Chinese is the document object model. Therefore, the text must be structured to continue processing. Not only the browser, but the parsing of the code must first go through the Parse stage.

For HTML link, img, script tags that need to load remote resources, the browser will call network thread to give priority to parallel processing, but when encountering script tags, it must stop and execute first, because js code may change any dom object, which may cause The browser needs to re-parse. So if your code does not modify the side effects of dom, you can add async, defer tags, or JS modules so that the browser does not have to wait for the execution of js.

Style calculation

Only the DOM is not enough. The style declared by the style tag needs to be applied to the DOM. Therefore, based on the DOM, the browser must generate a CSSOM. This CSSOM is mainly based on the css selector to determine the active node.

layout

With DOM and CSSOM, it is still not enough to draw a web page, because we only know the structure and style, but not the location of the elements. This requires the generation of LayoutTree to describe the structure of the layout.

LayoutTree and DOM structure are very similar, but display: none will not appear on LayoutTree, so LayoutTree only considers the rendering structure, and DOM is a comprehensive description structure, which is not suitable for direct rendering.

The original text specifically mentioned that LayoutTree has a big technical difficulty, namely typesetting. Chrome has a whole team dedicated to solving this technical problem. Why is typesetting so difficult? You can experience the tip of the iceberg from these few examples: collisions between box models, fonts spreading the content to cause line breaks, triggering a larger area re-typesetting, one box model spreading and squeezing another box model, but the size of the other box model changes Later, the content layout also changed, causing the box model to change again, which in turn led to the layout of other external box models.

The most difficult part of the layout is that it is necessary to deal with all the strange layout styles as reasonably as possible, and in many cases the rules of the layout styles conflict with each other. And this does not consider the risk of unknown BUGs caused by the modification of the layout engine on hundreds of millions of web pages.

Drawing

Is DOM, CSSOM, LayoutTree enough? Not yet, and the last link, PaintRecord, is missing. This refers to the drawing record. It records the hierarchical relationship of the elements to determine the order in which the elements are drawn. Because LayoutTree only determines the physical structure, but does not determine the upper and lower spatial structure of the element.

With DOM, CSSOM, LayoutTree, PaintRecord, you can finally draw. However, when HTML changes, the cost of redrawing is huge, because the calculation result of any step above depends on the previous step. When HTML changes, DOM, CSSOM, LayoutTree, and PaintRecord need to be recalculated.

Most of the time, the browser can complete it in 16ms, keeping the FPS at about 60, but when the page structure is too complicated, the calculation itself exceeds 16ms, or the blockage of the js code is encountered, the user will feel stuck. Of course, for the js stuck problem, you can use requestAnimationFrame to disperse the logic operation in each frame when it is idle, or it can be independent of the web worker.

synthesis

The drawing step is called rasterizing. When Chrome was first released, a simpler rasterization scheme was adopted, that is, only the pixels in the but area are rendered, and after scrolling, the pixels at the current scrolling position are supplemented and rendered. Doing so will cause rendering to always lag behind scrolling.

Nowadays, more mature compositing technology (compositing) is generally used, which is about layered rendering and rendering of rendered content, which can greatly improve performance, and can be will-change (don't abuse it).

The browser will analyze the LayoutTree to get the LayerTree (layer tree), and render it layer by layer.

The composition layer will divide the drawing content into multiple grids and hand them over to the GPU for rendering, so the performance will be very good.

intensive reading

Performance optimization from the perspective of rendering layering

This article mentions the five important links of browser rendering: parsing, style, layout, drawing, and composition. These are the deepest part of the browser in the daily work of front-end developers, and the part where optimization occurs the longest.

In fact, from the perspective of performance optimization, the parsing link can be replaced with the JS link, because modern JS frameworks often do not have any HTML template content to be parsed. Almost all JS manipulates the DOM, so it can be regarded as 5 new links: JS, style, Layout, drawing, compositing.

It is worth noting that the calculation of almost every layer depends on the result of the upper layer, but not every layer will necessarily be recalculated. We need to pay special attention to the following situations:

  1. Modifying the geometric properties of the element (position, width, height, etc.) will trigger the recalculation of all layers, because this is a very heavyweight modification.
  2. Modifying the drawing properties of an element (such as color and background color) does not affect the position, and the layout layer will be skipped.
  3. Modifying properties such as transform will skip the layout and drawing layers, which looks incredible.

Regarding the third point, since the content of transform will be promoted to the composition layer and handed over to the GPU for rendering, it will not be processed together with the layout and drawing of the browser's main thread, so visually this element does have a displacement, but it left and top are fundamentally different in realization.

So from the perspective of a browser developer, you can easily understand why this optimization is not a trick, because the implementation of the browser itself separates the layout, drawing and the behavior of the composition layer, and different code bottom solutions are different. , Performance will definitely be different. You can use csstriggers see which layers of recalculation are triggered by different css attributes.

Of course, as a developer, you can still left top transform the implementation details of 061b6b74299469 061b6b7429946a and 061b6b7429946b, and automatically perform reasonable layering", but if the browser manufacturer cannot do this, the developer still actively understands Realize the principle.

Implicit composite layer, layer explosion, automatic layer merging

In addition to the transform and will-change attributes, there are many situations where elements will be promoted to the composition layer, such as video , canvas , iframe , or fixed elements, but these have clear rules, so they belong to display composition.

The implicit composition refers to the situation where the element is not specifically marked but is also promoted to the composition layer. This situation usually occurs when the z-index element overlaps, and the lower element display statement is promoted to the composition layer. The browser should ensure that z-index To cover the relationship, the upper element must be implicitly promoted to the composite layer.

Layer explosion refers to the reason for implicit synthesis. When css has some complex behaviors (such as trajectory animation), the browser cannot capture which elements are located above the current element in real time, so all elements have to be promoted to the composite layer. When the number of composite layers Too much, the communication between the main thread and the GPU may become a bottleneck, which will affect performance.

The browser will also support automatic layer merging. For example, when implicitly promoted to a composite layer, multiple elements will be automatically merged into a composite layer. However, this method is not always reliable. After all, automatic processing cannot guess the intention of the developer, so the best way to optimize is for the developer to intervene actively.

We only need to pay attention to placing all the elements that are displayed on the composite layer z-index , so that the browser has a basis for judgment, and there is no need to worry about whether this element suddenly moves to the position of an element, causing that element to be suppressed. , So this element has to be implicitly promoted to the composition layer to ensure the correct order between them, because this element is originally located on top of other elements.

Summarize

After reading this article, I hope you can summarize more code-level performance optimization experience based on the implementation principle of the browser in the rendering process.

The last thing I want to complain about is that browser specifications are iterative gradually, so css attributes that seem to describe the position are actually implemented differently. Although this rule is reflected in the W3C specification, if only the attribute name is It is difficult to see the clues, so if you want to do the ultimate performance optimization, you must understand the principle of browser implementation.

The discussion address is: Intensive Reading "Understanding Modern Browser III" · Issue #379 · dt-fe/weekly

If you want to participate in the discussion, please click here , a new theme every week, weekend or Monday. Front-end intensive reading-to help you filter reliable content.

Follow front-end intensive reading WeChat public

<img width=200 src="https://img.alicdn.com/tfs/TB165W0MCzqK1RjSZFLXXcn2XXa-258-258.jpg">

Copyright notice: Freely reprinted-non-commercial-non-derivative-keep the signature ( Creative Commons 3.0 License )

黄子毅
7k 声望9.5k 粉丝