When you see this title, you will surely think of the divine article "how browsers work". This article talks about many details of the browser in detail, and it has also been translated into Chinese. Why do I want to write another one? For two reasons,
1) This article is too long and too expensive to read at one go.
2) You can learn a lot after reading this article with great effort, but it seems to be of little help to your work.
So, I am going to write this article to solve these two problems. I hope you can read it on your way to work or in the toilet, and learn something that can be used in your work.
Browser workflow
Let's cut the crap and take a look at the picture:
From the above figure, we can see the following:
1) The browser parses three things:
- One is HTML / SVG / XHTML. In fact, WebKit has three C + + classes corresponding to these three kinds of documents. Parsing these three files produces a DOM tree.
- CSS, parsing CSS will produce 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 will construct rendering tree through DOM tree and CSS rule tree. Be careful:
- Rendering tree a rendering tree is not the same as a DOM tree, because something like header or display: none doesn't need to be in the rendering tree.
- The main purpose of CSS rule tree is to complete matching and attach CSS rule to every element on rendering tree. That is, DOM node. That is the so-called frame.
- Then, calculate the position of each frame (that is, each element), which is also called layout and reflow process.
3) At last, we call the API of native GUI to draw.
DOM analysis
The DOM tree of HTML is parsed as follows:
The above HTML will be parsed as follows:
Here is another case with SVG tags.
CSS analysis
The parsing of CSS looks like the following (gecko is the way of Firefox). Suppose we have the following HTML documents:
So DOM tree looks like this:
Then our CSS document is as follows:
So our CSS rule tree will look like this:
Note that the fourth rule in the figure appears two times, one independent and one at the child node of rule 3. Therefore, we can know that the establishment of CSS rule tree is based on DOM tree. CSS matching DOM tree is mainly to parse CSS selectors from right to left. Many people think it will be faster, but it is not necessarily. The key also depends on how our CSS selector is written.
Note: CSS matching HTML elements is a fairly complex and performance issue. So, you will see a lot of people tell you that DOM tree should be small, CSS should use ID and class as much as possible, don't stack them in a transitional way
Through these two trees, we can get a style context tree, which is as follows (attach the CSS rule node to the DOM tree):
Therefore, Firefox basically generates CSS rule tree through CSS parsing, then generates style context tree by comparing DOM, and then Firefox completes by associating style context tree with its render tree (frame tree). Note: render tree will remove some invisible nodes. The so-called frame in Firefox is a DOM node. Don't be confused by its name.
Note: unlike Firefox, WebKit uses two trees to do this. WebKit also has a style object, which directly stores the style object in the corresponding DOM node.
Rendering
The rendering process is basically as follows (four steps in yellow):
- Calculate CSS Style
- Build render tree
- Layout - positioning coordinates and sizes, whether to wrap lines, various positions, overflow, Z-index properties
- Official opening of paintings
Note: there are many connecting lines in the above process, which means that JavaScript dynamically modifies the DOM property or CSS property, which will lead to a new layout. Some changes will not, that is, the arrows pointing to the sky, such as the modified CSS rule is not matched, etc.
Here are two important concepts: reflow and retain. These two are not the same thing.
- Repeat - part of the screen needs to be redrawn, for example, the background color of a CSS has changed. But the geometry of the element does not change.
- Reflow - this means that the geometry of the component has changed and we need to revalidate and calculate the render tree. Some or all of the render trees have changed. This is reflow, or layout. (HTML uses flow based layout, that is, flow layout, so if the geometric size of a component changes, it needs to be rearranged, which is called reflow.) reflow will start from the root Frame starts to recursively calculate the geometric size and position of all nodes in turn. During reflow, some frames may be added, such as a text string must be wrapped.
Here is a video of layout / reflow when opening Wikipedia (Note: HTML will also do reflow once during initialization, which is called internal reflow). You can feel it:
The cost of reflow is much higher than that of repaint. Every node in DOM tree will have reflow method. Reflow of a node may lead to reflow of child nodes, even parent nodes and peers. On some high-performance computers, it may not be much, but if reflow happens on mobile phones, the process is very painful and power consuming.
Therefore, the following actions are likely to be more expensive.
- When you add, delete or modify a DOM node, it will cause reflow or retain
- When you move the DOM, or do an animation.
- When you change CSS styles.
- When you resize the window (there is no problem with the mobile terminal), or when you scroll.
- When you change the default font for a web page.
Note: display: none will trigger reflow, while visibility: hidden will only trigger retain, because no location change is found.
Say two more sentences about scrolling. Generally speaking, if all the pixels on our page will scroll when scrolling, there is no problem in performance, because our video card is very fast for this algorithm of moving the full screen pixels up and down. But if you have a fixed background image, or some elements do not follow the scrolling, and some elements are animations, the scrolling action will be quite a painful process for the browser. You can see how bad many of these pages are when scrolling. Because scrolling can also cause reflow.
Basically, reflow has the following reasons:
- Initial. When the web page is initialized.
- Incremental。 When some JavaScript is operating DOM tree.
- Resize. The dimensions of some of its components have changed.
- StyleChange。 If the properties of CSS change.
- Dirty. Several reflows of incremental occur on the subtree of the same frame.
OK, let's take an example:
Of course, our browser is smart. It will not reflow or retain every time you change the style as above. Generally speaking, the browser will accumulate such operations and make a reflow, which is also called asynchronous reflow or incremental asynchronous reflow. But in some cases, the browser will not do so, such as: resize window, change the default font of the page, etc. For these operations, the browser will reflow immediately.
But sometimes, our script will prevent the browser from doing so. For example, if we request the following DOM values:
- offsetTop, offsetLeft, offsetWidth, offsetHeight
- scrollTop/Left/Width/Height
- clientTop/Left/Width/Height
- Getcomputedstyle() or currentstyle in IE
Because, if our program needs these values, then the browser needs to return the latest values, and this will flush out some style changes, resulting in frequent reflow / retain.
Reduce reflow / retain
Here are some best practices:
1) Don't change the DOM style one by one. Instead, it's better to predefine the class of CSS and then modify the classname of DOM.
2) Change DOM offline. Such as:
- Using the documentfragment object to manipulate DOM in memory
- First give the DOM to display: none (once reflow), and then change it as you want. For example, modify it 100 times, and then display it.
- Clone a DOM node into memory, and then change it as you want. After that, exchange it with the online one.
3) Do not put the attribute value of DOM node in a loop as a variable in the loop. Otherwise, it will lead to a large number of reading and writing properties of this node.
4) Modify the lower level DOM as much as possible. Of course, changing the DOM at the bottom of the hierarchy may cause a large area of reflow, but it may also have a small impact.
5) Using fixed or absault positions for animated HTML components, modifying their CSS will not reflow.
6) Never use a table layout. Because a small change may cause the whole table to be rearranged.
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 under ie, you don't know what you have modified. As a result, the CPU goes up to 100% in a flash, and then it takes several seconds to recover / reflow. This kind of thing often happens in the age of IE. So, we need some tools to help us see if there is anything inappropriate in our code.
- Under chrome, Google's SpeedTracker is a very powerful job to show you how much your browsing and rendering costs. In fact, both Safari and chrome can use a timeline in developer tools.
- The firebug based plug-in called firebug paint events in Firefox is also good.
- You can use an IE extension called dynatrace under ie.
Finally, don't forget the following articles to improve 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
Reference resources
- Speech by David Baron: fast CSS: how browsers lay out web pages: slideshow, all slides, audio (mp3), session page, lanyrd page
- How Browsers Work: http://taligarsiel.com/Projects/howbrowserswork1.htm
- Mozilla's style system overview: https://developer.mozilla.org/en-us/docs/style_system_overview
- Mozilla's note of reflow: http://www-archive.mozilla.org/newlayout/doc/reflow.html
- Rendering: repaint, reflow/relayout, restyle:http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/
- Effective Rendering CSS:http://css-tricks.com/efficiently-rendering-css/
- WebKit rendering document: http://trac.webkit.org/wiki/webcorerendering
Follow coolshell wechat public account and wechat applet
——===Visit cool shell 404 to find the missing child. = = = --
Loading...