Hello everyone, I am Lin Yiyi, this is an article about how browsers render a page formation principle, no more words, directly start to read 👍

001 browser bottom rendering page

Five processes in the browser

After obtaining the resources of the server, the browser parses THE HTML into a DOM tree and calculates the CSS into a CSSOM tree, synthesizing the two into a Render tree. The browser generates a page based on the Render Tree layout. It’s important to understand that the resources the browser gets back from the server are bits of bytecode 3C 6F 6E 62…. And so on, the browser will follow a set of specifications and the W3C will parse the bytecode into a string of code that we see.

The mechanism by which browsers load resources

  • The browser opens up a GUI rendering thread that executes the code from top to bottom, dedicated to rendering the rendered page.

Encountering CSS resources

  • encounter<style>The inline tag is handed to the GUI rendering thread for parsing, but is encountered<link>The tag is processed asynchronously, and the browser creates oneHTTPThe request processing thread, the GUI rendering thread continues to execute
  • If you encounter@importWill also open up a new oneHTTPRequest thread processing due to@importThe synchronized GUI rendering thread blocks waiting for the result of the request.

Note that in Chrome, a maximum of 6 to 7 HTTP request threads can be created for the same source.

Encounter JS resources

The bottom line represents the process of the GUI thread. The render thread encounters script resources in different situations and has different processing.

  • encounter<script></script>Resources, which are synchronized by default. The GUI rendering thread will block. The GUI thread will wait for the JS rendering thread to finish rendering before continuing rendering.
  • If you encounter<script async></script>Then the resource is asynchronousasyncThe browser will also open oneHTTPThe request thread loads the resource, and the GUI renderer thread continues rendering down. When the requested resource returns, the JS renderer thread starts executing, and the GUI thread blocks again.
  • If you encounter<script defer></script>Similar to Async will open up a new oneHTTPThe thread, the GUI continues rendering. Unlike Async,deferThe requested resource needs to wait for the GUI synchronization code to finish before executing the requested code from defer.

Async does not have resource dependencies. Defer needs to wait for all resource requests to come back and execute them in order of import/dependencies.

Picture or audio

  • encounter<img/>Asynchronously, a new HTTP thread is also opened to request the resource. The GUI continues rendering, and when the GUI finishes rendering, the requested resource is processed.

Note that: If some resources load slowly, the browser will ignore these resources and then render the following code. In Chrome, the preloader htMl-repload-scanner is used to scan the SRC and link nodes for preloading, avoiding the loading time of resources

Browse the mechanism for parsing resources

  • How does the browser parse the loaded resource file? One is determined when the page is rendered top-downThe DOM tree.CSSOM treeAnd the lastThe DOM treeCSSOM treeWill be merged intoRender tree, these so-called trees are actually JS objects, using JS objects to represent nodes, styles, and the relationship between nodes and styles.

The DOM tree

A DOM tree is defined as a parent-child or brotherly relationship between nodes. This is generated by the GUI rendering thread after the top-down rendering, and the CSSOM style tree is generated when the CSS resource request comes back.

CSSOM tree

CSSOM(CSS Object Model), after loading CSS resources will be rendered by the GUI into a style tree

Layout Tree Render tree

The browser generates a layout tree from the DOM tree and CSSOM tree to render the page through the following steps. Note that display:node nodes are not rendered into the Render Tree

  • Layout Layout according to the Layout treeFigure out the location and size of the node in the device.
  • Layering. Hierarchical processing according to hierarchical positioning
  • Painting page

The graph above is what the browser looks like after processing it

002 Browser Performance Optimization

To optimize the performance of the front-end browser, start with CRP: the critical rendering path

DOM Tree

  • Reduce DOM hierarchy nesting
  • Do not use standard labels

CSSOM

  • Try not to use@import, will hinder theGUIRender thread.
  • Less CSS code can be used inlinestyleTag to reduce requests.
  • To use lesslinkCan reduce the number of HTTP requests.
  • The CSS selector chain is as short as possible because CSS selectors are rendered from right to left.
  • Puts the link request written to<head></head>Internally, resources can be requested from the start and the GUI rendered at the same time.

Other resources

  • <script></script>As much as possible, synchronous JS resources are placed at the end of the page to prevent obstructionGUIThe rendering. If you encounter<script async/defer></script>The GUI rendering will not break, but the GUI rendering will be interrupted when the JS resource request comes back.
  • <img />Resources use lazy loading, lazy loading: Do not load images the first time the page is loaded, because images also occupy the HTTP volume. You can also use the image base64, which stands for picture.

To consider

Does CSS hinder DOM parsing and rendering?

CSS does not hinder DOM tree parsing, but it does hinder DOM tree rendering.

003 Refluxing and Redrawing

The layout stage is the backflow stage and the painting stage is the repainting stage. There must be a backflow and redraw the first time a page is loaded.

  • The process by which a browser renders a page

The browser first parses the HTML into a DOM tree to compute the DOM structure; Then load the CSS to parse into CSSOM; Finally, DOM and CSSOM are combined to generate a layout Tree, and the browser calculates the layout according to the page (rearrangement stage). Finally, the browser paints the page according to the Layout Tree (painting, repainting stage).

Rearrangement (DOM reflux)

Rearrangement refers to rearranging elements of a layout tree. Some DOM sizes and positions have changed (the layout and geometry of the page have changed). The process of rerendering the DOM is DOM rearrangement (DOM rearrangement). This is why the virtual DOM was introduced.

A rearrangement has occurred

  • The stage where the first page evaluates the layout
  • Add or remove DOM nodes that changelayout tree
  • Element position, element font size, and so on can also cause DOM backflow
  • The geometry of the node changes, for exampleWidth, height, border, padding,margin, etcBe changed
  • To find box propertiesOffsetWidth, offsetHeight, Client, ScrollThe browser will rearrange operations to get these attributes.
  • The framework ofv-ifThe operation can also cause backflow to occur.
  • , etc.

How many times has the following code been rearranged?

box.style.width = "100px";
box.style.width = "100px";
box.style.position = "relative";
Copy the code

You might think it’s 3 times, but in modern browsers, the browser creates a render queue for the above style code, puts all the render code in the queue for the last update, so the number of reorders is 1. Asking the following code will result in several rearrangements

box.style.width = "100px";
box.style.width = "100px";
box.offsetWidth;
box.style.position = "relative";
Copy the code

The answer is 2, because offsetWidth causes the render queue to refresh to get the exact offsetWidth value. Finally, position causes the position of the element to change and triggers a backflow. So there are two total times.

redraw

Redraw is when the style of the page has changed, but the DOM structure/layout has not. If the color changes, the browser will redraw the desired color.

A redraw has occurred

  • The stage of the first page painting
  • Element-coloredcolorchange

Direct synthesis

If we change a property that does not affect layout and drawing, the browser’s rendering engine skips the rearrangement and redrawing stages and goes straight to composition

  • For example, if we use the TRANSFORM property of CSS, the browser can synthesize the animation directly.

Rearrangement always leads to redrawing, but redrawing does not necessarily lead to rearrangement

Rearrange (DOM reflux) and redraw? Let me tell you the difference

How to reduce rearrangement and redraw…

The difference between

The rearrangement will cause the DOM structure to change, and the browser will need to rerender the layout to generate the page, but the redrawing will not cause the DOM to change, only the style change, which can be very performance costly.

How to reduce rearrangements and redraws

    1. Avoid the use oftableLayout, becausetableLayout calculation takes a long time and consumes performance;
    1. Style set changes, avoid using style too much, and instead modify class.
    1. Avoid frequent DOM manipulation and use vue/ React instead.
    1. Separate reads and writes of styles. Set the stylestyleAnd read stylesoffsetEqual separation can also reduce the number of backflow.
    1. Design the animation on top of the document flowpositionProperties of theabsolutefixedOn. Use GPU to accelerate synthesis.

reference

“Browser Working Principles and Practices”

Render Tree page rendering

The end of the

Browser Principles:Local storage and browser caching

Vue Principle:Vue high frequency principle detailed solution

Principles of Webpack:Write loader and plugin

Thank you for reading this. If this article inspires or helps you, please send it to 👍👍. I’m Yi-il Lin.