Originally the address

The Denver nuggets

github

Hello everyone, I’m Lin Yiyi, this is an article about how the browser renders a page to form the principle, without saying anything, just start reading 👍

001 Browser’s underlying rendering page

Five processes in the browser

Browser in the acquisition of server resources will be HTML parsing into DOM tree, CSS calculation into CSSOM tree, the synthesis of the two Render Tree. The following browser generates a page according to the Render Tree layout. It is important to understand that the resources the browser retrieves from the server are bytecode 3C 6F 6E 62…. The browser then parses the bytecode as a string of code in accordance with a set of specifications known as the W3C until we see the code.

The mechanism by which the browser loads resources

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

Encountering CSS Resources

  • encounter<style>The inline tag is given to the GUI renderer thread to parse, but encountered<link>Tags are processed asynchronously, and the browser creates oneHTTPThe thread that handles the request, the GUI rendering thread, continues to execute
  • If @import is encountered, a new HTTP request thread is also created for processing, since @import is synchronous and the GUI renderer thread will block waiting for the result of the request.

    Note that in Chrome, a maximum of 6-7 HTTP request threads can be opened simultaneously from the same source.

Encountering JS Resources

The bottom line represents the process of the GUI thread, the rendering thread encounters different situations of script resources, have different processing.

  • encounter<script></script>Resources, by default, are synchronized. The GUI rendering thread will block at this point. Wait for the JS rendering thread to finish rendering before the GUI thread continues rendering.
  • If you encounter<script async></script>Then the resource is asynchronousasync, the browser will also create oneHTTPWhen the requesting thread loads the resource, the GUI renderer thread continues to render down. When the requested resource returns, the JS renderer thread starts executing, and the GUI thread is blocked again.
  • If you run into like async, a new HTTP thread is created, and the GUI continues rendering. The difference between DEFER and ASYNC is that the deferred resource requested must wait for the GUI synchronized code to finish executing before executing the deferred code requested.

    Async does not have a dependency on the resource. DEFER waits for all resource requests to come back and executes in the same order/dependency as the import.

Pictures or Audio

  • encounter<img/>Asynchronous, also opens up a new HTTP thread to request resources. The GUI continues rendering, and when the GUI rendering is complete, the requested resource is processed.

It should be noted that if some resources load slowly, the browser will ignore these resources and then render the following code, in the Chrome browser will use the preloader HTML-repload-scanner to scan the SRC, link and other nodes in the first preload, to avoid the time of resource loading

Browse the mechanism for resolving resources

  • How does the browser parse the loaded resource file? One is determined when the page is rendered from top to bottomThe DOM tree.CSSOM treeAnd the lastThe DOM treeCSSOM treeIt’s going to be merged intoRender treeThese so-called trees are actually JS objects that represent nodes, styles, and the relationships between nodes and styles.

The DOM tree

The so-called DOM tree is to determine the parent-child and sibling relationships between nodes. This is generated by the GUI rendering thread at the end of the top-down rendering, and the CSSOM style tree is generated when the CSS resource request comes back.

CSSOM tree

CSSOM(CSS Object Model), CSS resources after loading back will be GUI rendered as
The style tree

Render tree Render tree

The browser needs to go through the following steps to Render the page based on the Render Tree. Pay attention to
display:nodeIs not rendered into the Render Tree

  • Layout, according to the render treeCalculate the position and size of the node in the device.
  • Layering. Layered processing according to hierarchical positioning
  • Painting page

The graph above is what the browser will look like after processing it

002 Browser Performance Tuning

Front-end browser performance optimization can start with CRP: Critical Render Path

DOM Tree

  • Reduce hierarchical nesting of the DOM
  • Do not use standard labels

CSSOM

  • Try not to use@import, will hinder theGUIThe render thread.
  • Less CSS code can be embeddedstyleTags to reduce requests.
  • To use lesslink, can reduce the number of HTTP requests.
  • The CSS selector chain is kept as short as possible because CSS selectors are rendered from right to left.
  • Places the written Link request into<head></head>Internally, resources can be requested from the start and the GUI rendered at the same time.

Other resources

  • <script></script>If possible, put synchronous JS resources at the end of the page to prevent obstructionGUIThe rendering. If you encounter<script async/defer></script>The GUI rendering will not interrupt, but the JS resource request will interrupt the GUI rendering.
  • <img />Resources use lazy loading, lazy loading: Do not load images the first time the page is loaded, as images will also take up HTTP volume. You can also use image base64 to represent the image.

003 Reflow and redraw pieces

The layout stage is the reflow stage of the page, and the painting stage is the redraw stage. The first time the page loads, there must be a reflow and redraw.

  • The flow of the browser rendering the page

    The browser will do it first
    HTMLParsed into
    The DOM treeTo calculate
    DOMStructure; Then load the
    CSSParsed into
    CSSOM; The final will be
    DOM and CSSOMMerge to generate the render tree
    Render Tree, the browser calculates the layout(rearrangement stage) according to the page; Finally, the browser follows
    render treePaint (the redraw phase) the page.

Rearrange (DOM backflow)

Rearrangement is refers to the
render treeSome of the
DOMThe size and position change (the layout and geometry information of the page change), and the browser rerenders
DOMThis is the process of
Rearrange (DOM backflow), rearrangement can consume a lot of performance on the page, which is why virtual DOM was introduced.

A rearrangement occurs

  • The stage of the first page to calculate the layout
  • Adding or deleting a DOM node has changedrender tree
  • The position of the element, the font size of the element, and so on can also cause DOM reflux
  • The geometric properties of nodes change, such asWidth, height, border, padding,margin, etcBe changed
  • Find the properties of the boxOffsetWidth, offsettheight, client, scrollAnd so on, the browser rearranges the actions in order to get these properties.
  • The framework ofv-ifThe operation can also cause backflow to occur.
  • , etc.

A small question, ask the code below the browser rearrangement of how many times (Chrome new browser based)?

box.style.width = "100px";
box.style.width = "100px";
box.style.position = "relative";

You might think it’s 3 times, but in modern browsers, the browser will create a render queue for the above style code, put all the render code in the queue, and update it for the last time, so the number of rearranges 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";

And the answer is 2 times because
offsetWidthWill cause a refresh of the render queue so that the exact
offsetWidthValue. The last
positionCausing a change in the position of an element also triggers a reflux. So there’s a total of two.

redraw

A redraw is when the style of the page has changed but
DOMThe structure/layout has not changed. For example, if the color changes, the browser will redraw the desired color.

A redraw has occurred

  • The first stage of page painting
  • element-coloredcolorchange

Direct synthesis

If we change a property that doesn’t affect layout or drawing, the browser’s rendering engine will skip the rearrange and redraw stage and go straight to compositing

  • For example, we use the transform property of CSS, and the browser can synthesize the animation effect.

A rearrange will always cause a redraw, but a redraw will not necessarily cause a rearrange

Do you rearrange and redraw the DOM? Let me tell you the difference

How does > reduce rearrangement and redrawing? How does > reduce rearrangement and redrawing?

The difference between

The rearrangement will cause
DOM structureThe browser needs to rerender the layout to generate the page, but the redraw does not cause a DOM change, just a stylistic change, which can consume a lot of performance.

How to reduce rearrangement and redrawing

    1. Avoid the use oftableLayout becausetableLayout calculation time is relatively long performance consumption;
    1. The style set changes, avoiding frequent use of style, and modifying the class instead.
    1. Avoid DOM and use Vue/React.
    1. Separate reads and writes of styles. Set the stylestyleAnd read styleoffsetEqual separation can also reduce the number of reflux.
    1. Design the animation on top of the document streampositionProperties of theabsolutefixedOn. Use GPU to accelerate synthesis.

reference

“How Browsers Work and Practice”

Render Tree page rendering

The end of the

Thank you for reading this article. If you can find any inspiration or help from this article, please send it to 👍. I’m Lin Yiyi.

Browser Principles:Local storage and browser caching

Principle of VUE:VUE high frequency principle detailed solution

Webpack Principles:Write Loader and Plugin

The nuggets collection

Making collection