Overview of browser rendering principles and rendering principles

Source: Internet
Author: User

[Switch] Introduction to rendering principles of browsers and introduction to rendering principles

How Browsers Work this article detailed a lot of browser details, but also has a Chinese translation version. Now, the reposted article is written by Chen Hao for the purpose of being on the way to Work, or you can read it in the restroom and learn something that can be used at work.

 

Browser Workflow

First look at a chart

, You can see:

1) the browser will parse three things.

* An HTML/SVG/XHTML file. In fact, Webkit has three C ++ classes corresponding to these three types of documents. Parsing these three files will generate a DOM Tree * CSS, and parsing CSS will generate a CSS Rule Tree * JavaScript script, mainly through dom api and cssom api to operate DOM Tree and CSS Rule Tree

2) After parsing, the browser engine constructs the Rendering Tree through the DOM Tree and CSS Rule Tree. Note:

* The Rendering Tree is not equivalent to the DOM Tree, because something like Header or display: none does not need to be placed in the Rendering Tree. * The CSS Rule Tree is mainly used to complete the matching and append the CSS Rule to each Element on the Rendering Tree, that is, the DOM node, that is, the so-called Frame. * Then, calculate the position of each Frame (that is, each Element), which is also called the layout and reflow processes.

3) Finally, call the Native gui api to draw

 

DOM Parsing

Parse the html dom Tree as follows:

The above HTML will be parsed as follows:

The following is another scenario with SVG labels:

 

CSS Parsing

CSS Parsing is like the following (Gecko is used in Firefox). Suppose we have the following HTML document:

<doc><title>A few quotes</title><para class="emph">  Franklin said that <quote>"A penny saved is a penny earned."</quote></para><para>  FDR said <quote>"We have nothing to fear but <span class="emph">fear itself.</span>"</quote></para></doc>

The DOM Tree looks like this:

Then our CSS document is like this:

/* rule 1 */ doc { display: block; text-indent: 1em; }/* rule 2 */ title { display: block; font-size: 3em; }/* rule 3 */ para { display: block; }/* rule 4 */ [class="emph"] { font-style: italic; }

Therefore, our CSS Rule Tree will be like this:

The fourth rule in the figure appears twice, one independent and one on the subnode of rule 3. Therefore, we can know that setting up a CSS Rule Tree is better than setting up a DOM Tree. CSS matches the DOM Tree by parsing the CSS Selector from right to left.

Note: matching HTML elements with CSS is quite complicated and has performance problems. So you may see many people tell you that the DOM tree is small and CSS should use id and class as much as possible. Do not cascade them over.

Through these two trees, we can get a Style Context Tree, that is, the following (Attach the CSS Rule node to the DOM Tree ):

Therefore, Firefox basically generates CSS Rule Tree through CSS parsing. Then, generate a Style Context Tree by comparing the DOM, and Firefox associates the Style Context Tree with its Render Tree (Frame Tree. Note: Render Tree removes invisible nodes. The so-called Frame in Firefox is a DOM node.

 

Note: Unlike Firefox, Webkit does not use two trees To Do This. Webkit also has a Style object, which directly stores the Style object on the corresponding DOM node.

 

Rendering

The rendering process is basically as follows (four steps in yellow ):

1. Calculate the CSS style

2. Construct a Render Tree

3. Layout-positioning coordinates and sizes, line breaks, positions, overflow, and z-index attributes

4. Formal painting

Note: There are many connection lines in the process. This indicates that JavaScript dynamically modifies the DOM attribute or CSS attribute. Some changes may cause Layout resetting, but not those that point to the arrows in the sky, for example, the modified CSS Rule is not matched.

 

Here we will talk about two concepts: Repaint and Reflow, which are not the same thing.

* Reflow -- redraw a part of the screen. For example, the background color of a CSS changes. However, the geometric size of the element remains unchanged.
* Repaint -- it means that the geometric size of the component has changed. We need to re-verify and calculate the Render Tree. Is a part or all of the Render Tree. This is Reflow, or Layout (HTML uses flow based layout, that is, stream Layout. Therefore, if the geometric size of a component changes, you need to re-layout it, that is, Reflow ). Reflow recursively calculates the geometric size and position of all nodes from the root frame of

 

The following is a video of Layout/Reflow when Wikipedia is opened (Note: HTML also performs a reflow called intial reflow during initialization). You can feel it:

 

The cost of Reflow is much higher than that of Repaint. Each node in the DOM Tree has a reflow method. The reflow of a node may lead to subnodes, or even reflow of parent nodes and peer nodes. There may be nothing on some high-performance computers, but if reflow occurs on some mobile phones, this process is very painful and consumes power.

 

Therefore, the following actions may be costly:

* When you add, delete, or modify a DOM node, Reflow or Repaint may occur.

* When you move the DOM position or make an animation

* When you modify the CSS style

* When you Resize the window (the mobile end does not have this problem) or scroll

* When you modify the default font of a webpage

Note: display: none triggers reflow, while visibility: hidden only triggers repaint, because no location change is found.

 

As for scrolling, if all the images on our page are rolled during screen scrolling, there is no performance problem, because our graphics card is very fast for this algorithm to move the full screen pixels up and down. However, if you have a fixed background image, or some elements do not scroll along, and some elements are animations, this scrolling action will be a very painful process for the browser. You can see that many of these web pages have poor performance when scrolling, because scrolling may also cause reflow.

 

Basically, reflow has the following reasons:

* Initail: When the webpage is initialized

* Incremental: Some JavaScript codes are used to operate the DOM Tree.

* Resize: when the size of some components changes

* Style Change: CSS attributes have changed.

* Dirty: several Incremental reflows occur on the subtree of the same frame.

 

Let's look at an example:

Var bstyle = document. body. style; // cache bstyle. padding = "20px"; // reflow, repaintbstyle. border = "10px solid red"; // reflow and repaint bstyle again. color = "blue"; // repaintbstyle. backgroundColor = "# fad"; // repaint bstyle. fontSize = "2em"; // reflow, repaint // new DOM element-reflow, repaintdocument. body. appendChild (document. createTextNode ('dude! '));

Of course, our browser is smart, and it will not reflow or repaint every time the style is modified. Generally, browsers accumulate such operations and reflow them once. This is called asynchronous reflow or incremental asynchronous reflow. However, in some cases, the browser does not do this, for example, the resize window changes the default font of the page. For these operations, the browser will immediately reflow.

 

However, sometimes our script will prevent the browser from doing this. For example, if we request the following DOM values:

* OffsetTop/Left/Width/Height

* ScrollTop/Left/Width/Height

* ClientTop/Left/Width/Height

* GetComputedStyle () or currentStyle in IE

Because if we need these values, the browser needs to return the latest values, and the same will flush out some style changes, resulting in frequent reflow/repaint

 

Reduce reflow/repaint

Below are some Best Practices:

1) do not modify the DOM style one by one. In this case, it is better to pre-define the css class and then modify the DOM className.

// badvar left = 10,top = 10;el.style.left = left + "px";el.style.top  = top  + "px"; // Goodel.className += " theclassname"; // Goodel.style.cssText += "; left: " + left + "px; top: " + top + "px;";

2) modify the DOM offline, for example:

* Use the documentFragment object to operate the DOM in the memory * first give the DOM to display: none (one reflow), and then change it as needed, for example, modify it 100 times, then, it is displayed as * clone a DOM node to the memory, and then change it as needed. After the change, switch it with the online one.

3) do not place the attribute values of DOM nodes in a loop or use them as variables in a loop. Otherwise, this will lead to a large number of reading and writing the attributes of this node.

4) modify the DOM with a lower level as much as possible. Of course, DOM with a lower level may cause a large area of reflow, but it may also have a small impact scope.

5) use the position of fixed or absolute for the HTML element of the animation. Then they will not reflow the CSS modification.

6) do not use table layout. A small change will lead to the re-layout of the entire table.

Fixed layout, CSS 2.1 Specification

In this manner, the user agent can begin to lay out the table once the entire first row has been received. Cells in subsequent rows do not affect column widths. Any cell that has content that overflows uses the ‘overflow’ property to determine whether to clip the overflow content.

Automatic layout, CSS 2.1 Specification

This algorithm may be inefficient since it requires the user agent to have access to all the content in the table before determining the final layout and may demand more than one pass.

 

Several tools and several articles

Sometimes, you will find that in IE, when you don't know what to modify, the CPU will suddenly go up to 100%, and then repaint/reflow will be completed after several seconds, this kind of thing often happens in the IE era. Therefore, we need some tools to help us check whether our code is inappropriate.

* In Chrome, Google's SpeedTracer is a very powerful tool that allows you to view the rendering size of your browser. In fact, both Safari and Chrome can use a Timeline tool in the developer tool.

* The Firebug-based Firebug Paint Events plug-in Firefox is also good.

* In IE, an IE extension called dynaTrace can be used.

 

Finally, I will share several articles to improve the browser performance:

* Google-Web Performance Best Practices

* Yahoo-Best Practices for Speeding Up Your Web Site

* Steve Souders-14 Rules for Faster-Loading Web Sites

 

Source: Chen Hao-Overview of browser rendering principles

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.