Brief introduction to the principle of the browser's rendering (Reprint)
In May 22, 2013 Chen Hao
See the topic you would think this article "How Browsers Work" God, this article details the many browser speaks very fine, but also have been translated into Chinese. Why do I still want to write? For two reasons,
1)This article is too long, the cost of reading too much, can not read.
2)Spent a lot of effort after reading this article can know a lot, but it seems to work is not what help.
So, I'm going to solve the two problems mentioned above to write this article. I hope you can on the way to work, or sitting toilet can be read, and can learn to work with.
Browser working processes
Cut the crap, first look at a map:
From this chart, we can see a few things:
1)The browser will analysis three things:
- One is HTML/SVG/XHTML, in fact, the Webkit has three C++ class corresponding to the three types of documents. Analysis of these three files will produce a DOM Tree.
- CSS, Analysis of the CSS can generate CSS rules tree.
- Javascript, The script, mainly to operate DOM Tree and CSS Rule Tree. by DOM API and CSSOM API
2)The parsing is complete, the browser engine to construct Rendering Tree through DOM Tree and CSS Rule Tree. Be careful:
- Rendering Tree render tree is not equal to the DOM tree, because some like Header or display:none. There is no need to put in the render tree.
- CSS Rule Tree is to complete the matching and the CSS Rule Element Rendering Tree attached to each of the. Is the DOM node. The so-called Frame.
- Then, calculated for each Frame (that is, each Element) position, which is also called layout and reflow process.
3)Finally, by calling the operating system Native GUI API drawing.
DOM analysis
The following DOM Tree analysis of HTML:
1 2 3 4 5 6 7 8 9 10 11 12 |
<html>
<html> <head> <title>Web page parsing</title> </head> <body> <div> <h1>Web page parsing</h1> <p>This is an example Web page.</p> </div> </body> </html> |
The above HTML will be parsed into such:
Here is another SVG tag on the case.
CSS analysis
CSS analysis is probably like the following (the main said is Gecko is the version of Firefox), suppose we have the following HTML document:
1 2 3 4 5 6 7 8 9 |
<doc>
<title>A few quotes</title> <para> Franklin said that <quote>"A penny saved is a penny earned."</quote> </para> <para> FDR said <quote>"We have nothing to fear but <span>fear itself.</span>"</quote> </para> </doc> |
So DOM Tree is like this:
Then our CSS document is this:
1 2 3 4 |
/* 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; } |
So we CSS Rule Tree would be like this:
Note, the fourth rule in figure appeared two times, once independent, once in the rule 3 child nodes. Therefore, we can know, the establishment of CSS Rule Tree is required by DOM Tree. CSS matching DOM Tree is mainly from right to left parsing of CSS Selector, a lot of people think that this thing will be faster, in fact is not necessarily. How key to see our CSS Selector wrote.
Note: the CSS matched HTML elements is a very complex and have performance problems. So, you will see a lot of people are telling you that in the N place, DOM tree should be small, as far as possible with the CSS ID and class, 10 million don't transition cascading down, ...
Through these two trees, we can get a call Style Context Tree, is the following (the CSS Rule node Attach to DOM Tree):
So, Firefox basically is through CSS CSS Rule Tree parsing and generation, Then, Through the ratio of DOM to generate Style Context Tree, Then Style Context Tree and the Render Tree through Firefox (Frame Tree) Association, Completed. Note: Render Tree will put some invisible nodes removed. WhileFirefox called Frame is a DOM node, don't be fooled by its name.
Note: unlike Webkit Firefox to use two trees to do this, Webkit also has a Style object, it directly to the Style object has the corresponding DOM node.
Rendering
The rendering process basically as follows (four steps yellow):
- Calculation of CSS style
- Construction of Render Tree
- Layout – Position and size, whether the line, all kinds of position, overflow, Z-index property ...
- Officially opened in painting
Note: the above process has a lot of connecting line, which expressed Javascript to dynamically modify the DOM attribute or CSS will lead to Layout, some changes will not, who refers to the sky arrow, for example, the modified CSS rule is not matching, etc.
Important here to say two concepts, one is Reflow, another is Repaint. These two are not the same thing.
- Repaint-A portion of the screen to redraw, such as a CSS background color. But the geometric dimension element does not change.
- Reflow-Mean size of components changed, we need to verify and calculate the Render Tree. Render Tree is a part or all of the changes. This is the Reflow, or Layout. (HTML is using flow based layout, so that flow layout,, if there is a change in geometry of a component, you need to re layout, also called reflow)The reflow from<html>The root frame recursive down, followed by calculation of the geometric size and location of all nodes, in the process of reflow, may increase the number of frame, such as a text string must be packaged.
Here is an open Wikipedia Layout/reflow video (Note: HTML at initialization time will do a reflow, called intial reflow), you can feel:
The cost of Reflow is much higher than the cost of Repaint. Each node in the DOM Tree will have a reflow method, a node reflow may well lead to sub node, even if the parent and sibling node reflow. In some high performance computer may not what, but if the reflow occurs in the mobile phone, so the process is very painful and power consumption.
So, these actions are likely to be high cost.
- When you add, delete, modify the DOM nodes, can lead to Reflow or Repaint
- When you move the position of the DOM, or when a animation.
- When you modify the CSS style.
- When you Resize window (mobile end does not have this problem), or rolling time.
- When you change the default font Webpage when.
Note: display:none will trigger the reflow, but visibility:hidden will trigger repaint, because did not find the position change.
Say a few words about the rolling screen, generally speaking, if when scrolling, pixel all our page will follow the rolling, so performance is not what problem, because our graphics to the screen pixel to move down the algorithm is very fast. But if you have a fixed background image, or some Element does not follow the scroll, some Elment animation, then the rolling action for the browser would be a very painful process. You can see the performance of many of these Webpage in rolling when there is poor. Because the rolling screen may also be caused by reflow.
Basically speaking, reflow has several reasons as follows:
- Initial. When Webpage initialization.
- Incremental. Some of the Javascript in DOM Tree.
- Resize. Some components of the size.
- StyleChange. If the CSS property changes.
- Dirty. Several Incremental reflow occurred in the subtree with a frame.
Well, let's look at an example:
1 2 3 4 5 6 7 8 9 10 11 12 |
var bstyle = document.body.style; // cache
bstyle.padding = "20px"; // reflow, repaint bstyle.border = "10px solid red"; //Again reflow and repaint bstyle.color = "blue"; // repaint bstyle.backgroundColor = "#fad"; // repaint bstyle.fontSize = "2em"; // reflow, repaint // new DOM element - reflow, repaint document.body.appendChild(document.createTextNode('dude!')); |
Of course, our browser is smart, it will not be like the one above, a style each you change, it is reflow or repaint a. In general, the browser will put up a number of such operations, then do a reflow, which is also called asynchronous reflow or incremental asynchronous reflow. But in some cases the browser is not going to do this, for example: resize window, change the page default font, etc.. For these operations, the browser will be reflow immediately.
But sometimes, our script will prevent the browser to do, such as: if some DOM we request the following values:
- offsetTop, offsetLeft, offsetWidth, offsetHeight
- scrollTop/Left/Width/Height
- clientTop/Left/Width/Height
- IE getComputedStyle (currentStyle), or
Because, if our program needs to these values, then the browser needs to return the new value, such as flush out some style changes, resulting in frequent reflow/repaint.
Reduction of reflow/repaint
Here are some of Best Practices:
1)Don't be a modification of the DOM style. Instead, as class defined CSS, and then modify the DOM className.
1 2 3 4 5 6 7 8 9 10 11 |
// bad var left = 10, top = 10; el.style.left = left + "px"; el.style.top = top + "px"; // Good el.className += " theclassname"; // Good el.style.cssText += "; left: " + left + "px; top: " + top + "px;"; |
2)The DOM offline after modification. Such as:
- Use the documentFragment object DOM in memory
- The DOM to display:none (a reflow), then you can change as you. Such as the 100 amendment, then he displayed.
- Clone a DOM node into memory, and then think how on how to change, after the change, and online at the exchange.
3)Don't put the attribute DOM node values as the cycle of variables in a loop. Otherwise it will lead to a number of properties to read and write this node.
4)As far as possible to modify the level is relatively low DOM. Of course, change the level is at the end of the DOM is likely to result in a large area of reflow, but also may affect the scope is very small.
5)The use of fixed or absoult as the HTML component of position animation, Then modify their CSS is not reflow.
6)Do not use table layout. Because a small change can cause the table to re layout may be very small.
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.
Fixed 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.
Automatic layout, CSS 2.1 Specification
Several tools and articles
Sometimes, you may find that in IE, you don't know what you changed things, the result of CPU was up to 100%, and then after a few seconds the repaint/reflow was completed, often happen in the IE era. Therefore, we need some tools to help us have a look our code has not what is not appropriate.
- Chrome, GoogleSpeedTracerIt is a very tough job to let you have a look your browser rendering cost much. In fact, Safari and Chrome can be used as a Timeline developer tools in the East.
- Firefox under the Firebug Firebug Paint plug-ins based on the Events.
- IE you can be extended by a man named dynaTrace IE.
Finally, don't forget the following several improved browser performance article:
- Google – Web Performance Best Practices
- Yahoo – Best Practices for Speeding Up Your Web Site
- Steve Souders – 14 Rules for Faster-Loading Web Sites
Reference resources
- David Baron's speech: Fast CSS: How Browsers Lay Out Web Pages: slideshow, all slides, audio (MP3), Session page, Lanyrd page
- How Browsers Work:
- Mozilla Style System Overview:
- Mozilla Note of reflow:
- Rendering: repaint, reflow/relayout, restyle:
- Effective Rendering CSS:
- The Webkit Rendering document:
(reprint the home station article please indicate the author and source cool shell – CoolShell.cn, do not be used for any commercial purposes)
The original address: http://coolshell.cn/articles/9666.html
Posted by Cathy at June 02, 2014 - 8:30 PM