preface

The previous article covered the navigation process of the browser, from the moment the user sends a URL request to the moment the page is parsed. The next article will cover the rendering process of the browser, from the moment the page is parsed to the moment the page is fully displayed.

We give HTML, CSS, JavaScript and other files to the browser, after some processing inside the browser can display a beautiful page, that before exploring how the browser internal processing, first review what HTML, CSS, JavaScript is:

  • HTML: The content of HTML is composed of tags and text. Each tag has its own semantics, and the browser will render the HTML content correctly based on the semantics of the tag.
  • CSS: Cascading style sheets, made up of selectors and properties, are used if you need to change the font color, size, and other information in your HTML.
  • JavaScript: JS for short, through JS can modify the page content, let the page “move” up.

These are the three main components of Web standards: structure, presentation, and behavior.

Browser to render HTML, CSS, JS into page is a complicated process, so in the rendering process will be divided into multiple sub phase, according to the time sequence can be divided into the following several stages: build a DOM tree calculation (CSS), obtain the layout, style, generate the layer tree, tree layer rendering, rasterize processing, synthesis of display.

Each of these sub-phases is described below, and each phase has a cycle of getting input, processing content, and producing output content, so focusing on these will make each sub-phase clearer.

Build a DOM tree

Browsers cannot understand and use HTML directly, so you need to translate HTML into a structure that browsers can understand – a DOM tree. DOM treats a document as a tree, where each node represents an HTML tag or text item within the tag.

DOM provides a structured representation of HTML documents. In the rendering engine, DOM serves three purposes:

  • From a page perspective, the DOM is the basic data structure for generating pages.
  • From a JavaScript scripting perspective, the DOM provides an interface for JavaScript scripting to manipulate, through which JavaScript can access the DOM structure to change the structure, style, and content of a document.
  • From a security perspective, the DOM is a line of security, and unsafe content is rejected during the DOM parsing phase.

In short, the DOM is the internal data structure that expresses HTML, connects Web pages to JavaScript scripts, and filters out unsafe content.

The process for building a DOM tree:

  • Input: AN HTML file retrieved from a network request or cache
  • To deal withThrough:The HTML parser generates a DOM treeTake the byte stream data of an HTML file, convert the byte data into a string, and then convert the string totag(token), and then make the marksLexical analysisintoDOMNode, and then willDOMnodeBuild as a DOM tree.
  • Output: Outputs a DOM tree structure, that is, the DOM tree.

DOM is almost identical to HTML content, but unlike HTML, DOM is stored in an in-memory tree structure that can be queried or modified using JavaScript.

Here, we can view the DOM by printing a Document or on Elements. Here is a simple EXAMPLE of a DOM tree:

Style calculation

The purpose of style calculation is to calculate the specific style of each element in a DOM node.

Like HTML, a rendering engine cannot directly understand the content of a CSS file, so it first parses it into a structure that browsers can understand, called styleSheets. There are a lot of places on the web to convert CSS files to CSSOM trees, while there is no CSSOM word in the Chromium source code, this styleSheets is intuitive to feel. But it doesn’t matter what the noun is, and I like the word CSSOM, it’s important that we understand the process of style calculation.

We can view the styleSheets structure through Document. styleSheets:

The process of style calculation:

  • The inputCSS styles come from three main sources:
    • throughlinkExternal CSS file referenced
    • <style>CSS inside the tag
    • Elements of thestyleProperty to embed CSS
  • To deal with:
    • Convert CSS to a structure that browsers can understandstyleSheets.styleSheetsIt has two functions:
      • The first is to provide JavaScript with the ability to manipulate style sheets;
      • The second is the style information that provides the basis for composing layout trees.
    • Transform property values in the stylesheet to standardize them; All values need to be converted into standardized computed values that the rendering engine can easily understand
      • For example:2emconvert32pxAnd theblueconvertrgb(0, 0, 255)And thefont-weight: boldconvertfont-weight: 700
    • Figure out the specific style of each node in the DOM treeIn this process, you need to follow the inheritance and cascading rules of the CSS
      • CSS inheritance is when each DOM node contains the style of its parent node
      • Cascading is a fundamental feature of CSS. It is an algorithm that defines how to combine property values from multiple sources.
  • Output: The style of each DOM node and is saved in the ComputedStyle structure.

You can press F12 to open the developer tool and select any Elements and then Computed tag, as shown in the figure below. The red box in the lower right corner shows the ComputedStyle value of the selected tag. With this in mind, is it convenient to change the style of the built-in components

Get the layout tree

Now that you have the DOM tree and the styles for each element in the DOM tree, you can’t render a full page yet because the browser doesn’t know the geometry of the elements on the page. So the next step is to calculate the geometry of the visible elements in the DOM tree, known as the Layout.

Layout stage:

  • Enter: DOM tree and CSSOM tree
  • To deal with:
    • Build a layout tree that contains only visible elements
      • Walk through all the visible nodes in the DOM tree and add them to the layout tree
      • Invisible nodes are ignored by the layout tree, such as property containsdispaly:noneElements are not wrapped in the layout tree
    • Layout calculation: Calculates the coordinate positions of nodes in the layout tree and writes them back into the layout tree
  • Output: A layout tree containing the style and location of DOM elements

The image below (from rendering flow (part 1) : How do HTML, CSS and JavaScript become pages?) :

Generate layer tree

After obtaining the layout tree, it needs to be layered, just as if its X and y axes are fixed, and then its Z axis is processed. The z-index z-axis sorting properties, position positioning properties, opacity and other properties can be reflected in CSS. Some complex effects can be achieved by layering, such as 3D transformation and page scrolling, etc. In order to achieve these effects more easily, the rendering engine will generate special layers for specific nodes and generate a corresponding LayerTree. The concept of layers will be much easier to understand if you know Photoshop.

Of course, not every node in the layout tree contains a layer. If a node has no corresponding layer, then the node is subordinate to the layer of the parent node. The rendering engine will create a new layer for a particular node only if one of the following two conditions is met:

  • First, owningCascading context propertiesThe element is promoted to a separate layer.
    • Elements that have explicitly positioned attributes, elements that define transparent attributes, elements that use CSS filters, and other elements that have cascading context attributes
  • The second point,Where you need to cutIt will also be created as a layer.
    • Pruning is those whose content is outside the specified area, such as onedivIts size is zero200 * 200Pixel, when the text content inside is too much beyond200 * 200The rendering engine creates a separate layer for the text section, and if a scrollbar appears, the scrollbar is promoted to a separate layer.

You can check this layer by opening Chrome’s Developer tool Layers, which is not displayed in the default tool. It is in the upper right corner. In More Tools, it has some operations such as translation, rotation and reset, as shown below:

Layer tree generation process:

  • Input: Layout tree
  • To deal with: Generates a dedicated layer for a specific node
    • Elements with cascading context attributes are promoted to a separate layer
    • Areas that need to be cropped will be created as layers
  • Output: Layer tree

Layer to draw

After building the layer tree, the rendering engine will draw each layer in the tree. It will break the drawing of a layer into many small drawing instructions, and then put these instructions in order into a list of layers to draw.

The instructions in the draw list are actually very simple, just ask it to perform a simple draw operation, such as draw a pink rectangle or black line, etc. Drawing an element usually requires several drawing instructions, because each element’s background, foreground, and borders require separate instructions to draw. So in the layer drawing phase, the output is these lists to draw.

As shown in the picture below, open the Layers tool in Chrome’s Developer tool and select the Document layer to actually experience the drawing list. The left area is the drawing list of Document. Drag the progress bar in the right area to reproduce the drawing process of the list.

Layer drawing process:

  • Enter layer tree
  • To deal with:
    • The rendering engine draws each layer in the layer tree
    • Split it into draw instructions, generate a draw list, and submit it to the composition thread
  • Output: Draw a list

Rasterization

A draw list is simply a list of draw orders and draw instructions that are actually done by the compositing thread in the rendering engine.

When the drawing list of layers is ready, the main thread submits the drawing list to the composition thread. Usually a page may be large, but the user can only see part of it. We call the part of the page that the user can see the viewport. In some cases, some layer can be very big, such as some pages you use the scroll bar to scroll to scroll to the bottom for a long time, but through the viewport, users can only see a small portion of the page, so in this case, to draw out all layer content, will generate too much overhead, but also it is not necessary.

For this reason, the composition thread will divide the layer into tiles, which are usually 256×256 or 512×512.

The compositing thread prioritizes bitmap generation based on the blocks near the viewport, and the actual bitmap generation is performed by rasterization. Rasterization refers to the transformation of a map block into a bitmap. The graph block is the smallest unit for rasterization. The renderer process maintains a rasterized thread pool, where all rasterization of blocks is performed.

Generally, GPU is used to accelerate the generation of bitmaps during rasterization. The process of using GPU to generate bitmaps is called fast rasterization, or GPU rasterization. The generated bitmaps are stored in GPU memory.

Rasterization process:

  • Enter: Draw a list
  • To deal with:
    • Depending on the viewport, the composition thread will divide the layer into blocks
    • The compositing thread prioritizes bitmap generation based on the blocks near the viewport
  • Output: bitmap saved in GPU memory

Synthetic display

  • Once all the tiles are rasterized,Synthesis of the threadA command to draw a graph block — is generatedDrawQuadAnd then submit the command toBrowser process
  • There’s a browser process calledvizComponent to receive messages from the composite threadDrawQuadCommand, and then draw its page contents into memory, which is finally displayed on the screen.

So in the display phase, the page is loaded and displayed, and that’s the whole process.

The image below (from rendering flow (below) : How do HTML, CSS and JavaScript become pages?) :

Summary of rendering process

  • The browser can’t understand the HTML data directly, so the first step is for the renderer to translate it into a DOM tree structure that the browser can understand
  • After generating the DOM tree, the rendering engine transforms the CSS stylesheet into something that the browser can understandstyleSheets.Figure out the style of the DOM node
  • Create a layout tree and calculate the layout information for DOM elements so that they are stored in the layout tree
  • Layer the layout tree and generate the layer tree
  • Generate a draw list for each layer and submit it to the composition thread
  • The composite thread divides the layer into blocks and converts the blocks into bitmaps in the rasterized thread pool
  • The composite thread sends the draw block command to the browser process. The browser process generates the page from the command message and displays it on the monitor

The above is a macro view of the browser rendering process, referring to geek time teacher Li Bing “Browser working Principles and Practice”, this is a very good column, recommended reading.

Browser series column directory