How does the browser render the page when we enter a URL?

In this case, the browser process sends the URL request to the network process via interprocess communication (IPC), where the network process initiates the actual URL request process after receiving the URL request.

  1. First of all, the network will find whether local cache cache the resource, if there is a cache resources, then return resources to the browser process directly, if there is no check to the resource in the cache, then directly into the network request process, this request before the first step is to process the DNS, request for domain name server IP address, If the request protocol is HTTPS, you also need to establish a TLS connection.
  2. The next step is to use the IP address to establish TCP connection with the server. After establishing the connection, the browser side will construct the request line, request first-class information, and attach the Cookie and other data related to the domain name to the request head, and then send the constructed request information to the server.
  3. After receiving the request information, the server will generate response data (including response line, response header, response body and other information) according to the request information and send it to the network process. After receiving the response line and response header, the network process begins to parse the content in the response header.
    • Redirect. After receiving the response header from the server, the network process begins to parse the response header. If the status code returned is 301 or 302, the server needs the browser to redirect to another URL. Then make a new HTTP or HTTPS request and start all over again.
    • The content-Type is a very important field in the HTTP header that tells the browser what Type of response body data the server is returning. The browser then uses the value of the Content-Type to determine how to display the response body Content.

Prepare the render process

By default, Chrome assigns a render process to each page, meaning that a new render process is created for each new page opened.

However, if a new page is opened from one page and belongs to the same site as the current page, the new page will reuse the parent page’s rendering process.

Once the renderer process is ready, it cannot immediately enter the document parsing state because the document data is still in the network process and has not been submitted to the renderer process, so the next step is to submit the document.

Submit the document

Submitting a document means that the browser process submits the HTML data received by the web process to the renderer process as follows:

  1. First, when the browser process receives the response header data from the web process, it sends a message to the renderer processSubmit the documentThe news.
  2. The renderer process receivesSubmit the documentAfter the message, the network process and the establishment of data transmission pipeline.
  3. After the document transfer is complete, the renderer process will returnConfirm to submitTo the browser process.
  4. The browser process is receivingConfirm to submitAfter the message, the browser interface state is updated, including the security state, the URL for the address bar, the forward and backward historical state, and the updated Web page.

At this point, a complete navigation process is completed, and then it is time to enter the rendering phase.

Rendering phase

According to the chronological order of rendering, the pipeline is divided into the following sub-stages:

  • Build a DOm tree
  • Calculate the style
  • The layout phase
  • layered
  • draw
  • block
  • rasterizer
  • synthetic
Build a DOM tree

Browsers can’t understand and use HTML, so you need to transform HTML into a structure that browsers can understand – a DOM tree

Now that we have generated the DOM tree, we still don’t know the style of the DOM node. To get the DOM node to have the correct style, we need to calculate the style.

  1. Input: HTML document;
  2. Processing: HTML parser parsing;
  3. Output: DOM data deconstruction;
Calculate the style
  1. Convert CSS to a structure that browsers can understand
  • External CSS files referenced by link
  • <style>Styles within the tag
  • Element’s style property is embedded with CSS

Convert the above three TYPES of CSS text into a structure that browsers can understand –styleSheets; 2. Transform property values in the stylesheet to standardize them

  1. Figure out the specific style of each node in the DOM tree

Now that the style properties have been standardized, it’s time to calculate the style properties for each node in the DOM tree

Use CSS inheritance rules and cascading rules to calculate the specific style of the tag 1. Input: CSS text 2. Processing: attribute values standardized, each node specific style (inheritance, cascade); 3. Output: styleSheets(CSSOM)

The layout phase

We use the DOM tree and the style of the elements in the DOM tree, but this is not enough to display the page, because we do not yet know the geometry of the DOM elements, so we need to calculate the geometry of the visible elements in the DOM tree, we call this calculation process layout.

Chrome performs two tasks in the layout phase: creating a layout tree and calculating the layout.

  1. Creating a layout tree

The DOM tree contains many invisible elements, such as the head tag and elements that use the display: None attribute. Before displaying them, we need to build an additional layout tree that contains only courseware elements.

To build the layout tree, the browser basically does the following:

  • Iterate through all visible nodes in the DOM tree and add these nodes to the layout tree;
  • Invisible nodes are ignored by the layout tree, such as everything under the head tag, or the body. P.pan element, which contains display: None, is not included in the layout tree
  1. Layout calculation

Now that we have a complete layout tree, it is time to calculate the coordinate positions of the nodes in the layout tree. Save this information in the layout tree.

  1. Enter: DOM & CSSOM to merge into render tree
  2. Processing: Layout tree (visible elements in DOM tree)
  3. Output: Layout tree
layered

Because there are many complex effects on the page, such as some complex 3D transformations, page scrolling, or z-index sorting, the rendering engine also needs to generate a layer tree for a particular node to make these effects easier.

The browser page is actually divided into many layers, which are superimposed to create the final page.

Not every node in the layout tree contains a layer. If a node has no corresponding layer, then the node is subordinate to the parent node’s layer

So what criteria does the rendering engine need to meet to create a new layer for a particular node? Two things are usually true

  1. Elements with cascading context attributes are promoted to a separate layer, elements with explicitly positioned attributes, elements with transparent attributes, elements with CSS filters, and so on, all have cascading context attributes.

2. Places that need to be clipped will be created as layers

div {
    width: 200px;
    height: 200px;
    overflow: auto;
    background: gary;
}
Copy the code

We limit the size of div to 200200 elements, and there is a lot of text content in div. The area displayed by the text will definitely exceed 200200. At this time, clipping is generated, and the rendering engine will use part of the clipped text content to display in the div area

When this clipping happens, the rendering engine creates a separate layer for the text section, and if the scroll bar appears, the scroll bar is promoted to a separate layer.

  1. Input: Layout tree
  2. Processing: Elements in the layout tree that satisfy the layering condition
  3. Output: layerTree
Layer to draw

After drawing the layer tree, the rendering engine will draw each layer in the tree

The rendering operation is 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

  1. Input: layerTree;
  2. Processing: split into draw instructions, generate draw list, submit to the synthesis thread
  3. Output: Draw a list
Rasterization operation

Usually a page may be large, but the user can only see part of it. We call the part that the user can see a viewport.

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

The compositing thread generates bitmaps in preference to blocks near the viewport. The actual bitmap generation is performed by rasterization, which translates blocks into bitmaps.

  1. Input: Draw a list;
  2. Processing: The composition thread will generate bitmap first according to the map block near the viewport;
  3. Output: bitmap.
Composition and display

Once all the tiles have been rasterized, the composition thread generates a command to draw the tiles -DrawQuad, which it then submits to the browser process

The browser process has a component called viz that receives DrawQuad commands from the compositing thread, draws its page contents into memory, and displays them on the screen.

  1. Input: bitmap;
  2. Processing: The composite thread issues the command -drawquad to the main thread
  3. Output: Final display on the screen.
Step to summarize

A complete rendering process can be summarized as follows:

  1. The renderer converts HTML content into a readable DOM tree structure;
  2. The rendering engine converts CSS styleSheets to browser-readable styleSheets and calculates the STYLES of DOM nodes.
  3. Create a layout tree and calculate the layout information of elements.
  4. Layering the layout tree and generating the layering tree;
  5. Generate a draw list for each layer and submit it to the composition thread;
  6. The composition thread divides the layer into blocks and converts the blocks into bitmaps in the raster thread pool.
  7. The composite thread sends the DrawQuad command to the browser process.
  8. The browser process generates a page from the DrawQuad message and displays it on the monitor.

rearrangement

Updating the geometry of an element, such as changing its width, height, etc., triggers the browser to rearrange the layout, a series of sub-stages after parsing. This process is called rearrangement, and rearrangement requires updating the entire rendering pipeline, so it is also the most expensive.

redraw

Update element mapping attribute, if change the background color of the element, so the layout phase will not be implemented, so did not cause the transformation of geometric position, so it directly into the rendering stage, and then execute after a series of stages, this process is called re-paint, compared with rearrangement, redrawn saves the layout and hierarchy, So the execution efficiency will be higher than the platoon operation.

synthetic

Direct synthesis stage, using the CSS transform to achieve animation effects, it can avoid the rearrangement and re-paint, directly in the main thread animation operation performed on the synthesis, the efficiency is highest, because is the main thread on synthesis, did not take up the resources of the main thread, but also avoids the layout and draw two child stage, Therefore, compared with redrawing and rearranging, composition can greatly improve the drawing efficiency

How to reduce redraw rearrangements in development

  1. Use class to manipulate styles rather than frequently manipulating styles
  2. Avoid table layouts
  3. Batch DOM manipulation, such as createDocumentFragment, or using frames (frames use virtual DOM technology to minimize DOM manipulation
  4. Window resize events with a high probability of triggering need to be throttled