preface

Browser rendering mechanism is almost an interview question, today read a few articles, do a summary of knowledge points! It can be divided into the following four main aspects:

  • ! DCTYPE
  • The main steps of browser rendering
  • The main concepts of reflow and repaint, trigger conditions, and how to avoid them as much as possible.

A,! DCTYPE

concept

<! The DOCTYPE> tag is not an HTML tag, but rather reminds the browser which HTML version to use to parse the page. Let’s take a quick look at some HTML protocols

HTML 4.01 Strict (contains all HTML elements and attributes, excluding display elements, deprecated elements, and framesets)

<! DOCTYPE HTML PUBLIC"- / / / / W3C DTD HTML 4.01 / / EN" "http://www.w3.org/TR/html4/strict.dtd">Copy the code

HTML 4.01 Transitional (contains all HTML elements and attributes, including display elements, deprecated elements, framesets)

<! DOCTYPE HTML PUBLIC"- / / / / W3C DTD HTML 4.01 Transitional / / EN" 
"http://www.w3.org/TR/html4/loose.dtd">Copy the code

HTML 4.01 Frameset (This DTD is equivalent to HTML 4.01 Transitional, but allows Frameset content.)

<! DOCTYPE HTML PUBLIC"- / / / / W3C Frameset DTD HTML 4.01 / / EN" 
"http://www.w3.org/TR/html4/frameset.dtd">Copy the code

HTML 5

<! DOCTYPE html>Copy the code

Why is there no reference to DTD in HTML5? Because HTML4.01 is based on SGML and DTDS prescribe rules for markup languages, so it is required. HTML5 is not based on SGML so it is not required.

The question of how the browser interprets the page is the same as the question of how the browser interprets the page. What about DOCTYPE>?

Second, the main steps of browser rendering

  1. The browser parses the HTML document into a DOM tree. (In this step, the browser starts parsing by starting another thread to download other CSS, JS, static resources, etc., but stops when it hits a
  2. After the CSS is downloaded, the CSS file is parsed into CSS objects, and then the CSS objects are assembled to generate the CSSOM tree.
  3. When both the DOM and CSSOM trees are built, the browser builds one from the DOM and CSSOM treesRender tree(rendering tree) represents a series of objects to be rendered.
  4. The browser streams each node in the rendering tree to calculate its position on the screen, a step called layout layout.
  5. Walk through the render tree and draw it to the screen. This step is called painting.

Here’s a graphic illustration of the process:

Three, the specific process of rendering

1. The browser parses the obtained HTML document into a DOM tree

When the browser receives the HTML document from the server, it traverses the document nodes to generate a DOM tree. Note the following points:


  • The DOM tree may be blocked by CSS and JS loading during construction
  • display:noneThe element will also be in the DOM tree
  • Annotations are also in the DOM tree
  • scriptThe tag will be in the DOM tree


Both DOM and CSSOM need to go through the process of Bytes→characters→ Tokens → Nodes → Object Model, as shown below:

When the browser receives the HTML document from the server, it traverses the document nodes to generate a DOM tree. Note the following points:

  • The DOM tree may be blocked by CSS and JS loading during construction
  • display:noneThe element will also be in the DOM tree
  • Annotations are also in the DOM tree
  • scriptThe tag will be in the DOM tree

Both DOM and CSSOM need to go through the process of Bytes→characters→ Tokens → Nodes → Object Model.




DOM tree generation can be blocked by CSS and JS load execution, as described in the next chapter. When the HTML document has been parsed, the browser continues loading the script marked as Deferred, and then the DOMContentLoaded event is triggered at the actual end of the parsing process, and the Load event is triggered after the Async document has finished executing.

2. CSSOM tree

The browser parses the CSS file and generates a CSSOM. Each CSS file is parsed into a StyleSheet Object, and each Object contains Style Rules, also known as CSSOM (CSS Object Model). CSS rule objects contain selectors and declaration objects corresponding to CSS syntax, as well as other objects. Some things to note in this process are:

  • CSS parsing can be done simultaneously with DOM parsing.
  • CSS parsing andscriptIs mutually exclusive.
  • In the Webkit kernelscriptPerform optimizations where mutual exclusion occurs only when JS accesses CSS.

3. rendering tree

Render Tree construction is essentially a DOM Tree and CSSOM Attach process (each DOM node has a Attach method). The browser will traverse each visible node starting from the root of the DOM Tree, and then find suitable CSS style rules for each visible node and apply them.

There are a few things to note in the rendering tree phase:

  • Render Tree and DOM Tree are not exactly the same.
  • Since the Render Tree is what will be displayed in the future, tags such as head will not be displayed in it.
  • Display: None Elements with this property are not displayed in the render tree.
  • Visibility: Hidden Elements that have this property will be displayed in the render tree.

After the rendering tree is generated, it still cannot be rendered to the screen, because the position of each node cannot be determined. At this time, the fourth step layout layout is entered.

4. The layout layout.

After we have created the Render tree, we can walk through it because each node in the tree has a Render Object that contains information about the width and height of the node, the background color, and so on. We can calculate the correct position information for each render object and render it to the correct position. This process is also known as backflow or layout, and it is possible to make changes to the DOM after loading js, which triggers the browser to rearrange (backflow) as I will write later. The output of the layout phase is known as the box model, which accurately captures the exact position and size of each element on the screen. Note that:

  • floatElements,absoulteElements,fixedThe element is positional offset.
  • When we talk about leaving the document stream, we really mean leaving the Render Tree.

5. Painting the render tree

In the paint phase, the browser traverses the render tree, calling the renderer’s paint() method to display its contents on the screen. The rendering tree is done by the browser’s UI back-end component.

Block rendering

When an HTML page is parsed by a browser, the internal script will wait until the script finishes executing if it encounters <script>, or the external script will wait until the script is downloaded before parsing the page.

If the JS script also operates on the CSS and the CSSOM tree is not built, the loading of the JS script will stop until the CSSOM tree is built. Because the CSSOM tree contains the style information of each node, there is no way to proceed to the next stage until the CSSOM tree is loaded, and the user sees the page blank until then. That’s why you put your CSS code in the <head> tag.

Why script tags are encountered is to stop parsing HTML documents, because JS scripts may contain operations on the DOM or CSSOM, script parsing will change the DOM and CSS in the script, respectively, and append to the DOM tree and CSSOM rule tree.

Reflow and Repaint

1. The reflux (reflow)

Backflow is simply a change in the layout of the page, and the browser needs to recalculate the location, size, and other information of each node, recursively from the root frame down. The process of going back and recalculating is called reflux. Backflow is inevitable, and it is not known which parts of the page are affected, because they are interdependent and interact with each other.

Reflux is caused by:

  • When the page is initialized
  • DOM manipulation (element addition, deletion, modification, element order change)
  • Content changes, including text changes in form fields
  • CSS properties are calculated or changed
  • Add or remove stylesheets
  • Change the Class property
  • Browser window zooming, scrolling, etc
  • Pseudoclass activation (e.g. Hover)
  • JS fetching Layout property values (e.g., offsetLeft, scrollTop, getComputedStyle, etc.) also causes backflow. Because the browser needs to backflow to calculate the latest value




Backflow must cause redrawing, but redrawing does not necessarily cause backflow.

2. Redraw (repaint)

Redraw is when the appearance of an element has been changed, the background color, text color, border color, etc. This causes the browser to redraw a section, but does not change the layout of the page.

In other cases, such as changing the style of an element, the browser does not immediately respond
reflowor
repaintOnce. Instead, you accumulate a batch of these operations and do them once
reflowThis is also called asynchrony
reflowOr incremental asynchrony
reflow. But in some cases, for example
resizeWindows, changed the page default font and so on. The browser does this right away
reflow.



How to avoid backflow and redrawing

  • You can set up DOM elements that need to be modified multiple timesdisplay:none, and then display after operation. The hidden element is not thererenderTree, so modifying hidden elements does not trigger backflow redraw)
  • withtransformDo deformation and displacement can be reducedreflow

  • When it is displayed that multiple DOM nodes need to be created after the operation is completed, use The DocumentFragment to create the document once
  • Cache Layout property values, such as var left = em.offsetLeft; In this way, multiple uses of left produce only one reflux
  • Avoid table layouts as much as possible (a table element that triggers backflow causes all other elements in the table to backflow)
  • Remove complex node elements from document flow by absolute displacement, forming a new Render Layer and reducing backflow costs
  • Avoid USING CSS expressions because each call recalculates the value (including loading the page)
  • Use CSS attribute abbreviations as far as possible, e.g., “border” instead of “border-style”, “border-color” Elem. ClassName and elem. Style. CssText replace elem. Style

7. Some suggestions for browser optimization

  • Write HTML and CSS legally, and don’t forget the document encoding type.
  • The style file should be inheadTag, while the script file is inbodyBefore ending, this can prevent blocking the way.
  • Simplify and optimize CSS selectors to minimize nesting layers.
  • Multiple reads (or writes) of the DOM should be placed together. Do not add a write operation between two read operations.
  • If a style is rearranged, it is best to cache the results. Avoid rearranging your browser the next time you use it.
  • Don’t change styles one by one, but by changeclassOr,csstextProperty to change the style once and for all.
  • As far as possible withtransformTo do deformation and displacement
  • Try to use the offline DOM instead of the real Web DOM to change element styles. For example, operationsDocument FragmentObject, and when you’re done, add that object to the DOM. Another example is usingcloneNode()Method, perform operations on the cloned node, and then replace the original node with the cloned node.
  • Let’s set the element todisplay: none(requires 1 rearrangement and redraw), then perform 100 operations on the node, and finally restore the display (requires 1 rearrangement and redraw). That way, you have two re-renders instead of maybe 100.
  • positionProperties forabsoluteorfixedThe rearrangement will be less expensive because there is no need to consider its effect on other elements.
  • Use the element only when necessarydisplayProperty is visible because invisible elements do not affect rearrangement and redraw. In addition,visibility : hiddenElements of are only affected by redrawing, not rearrangement.
  • usewindow.requestAnimationFrame(),window.requestIdleCallback()These two methods regulate re-rendering.

Finally, this article uses the following articles for reference, thank you!

  • https://www.jianshu.com/p/e6252dc9be32
  • https://blog.csdn.net/csdnnews/article/details/95267307
  • https://blog.csdn.net/liujianfeng1214/article/details/86690284