Introduction to Browser rendering principles

Source: Internet
Author: User

Translated from: http://kb.cnblogs.com/page/178445/

See this title everyone will think of this Browsers "How to Work", this article on the browser a lot of details are very detailed, but also translated into Chinese. Why do I want to write an article? For two reasons,

1) This article is too long, the cost of reading too much, can not read a breath.

2) It took a lot of effort to read this article, but it seemed to be of little help to the job.

So, I'm going to write down this article to solve both of these problems. Hopefully you'll be able to read it on your way to work or on the toilet, and learn something you can use at work.

  Browser work Large process

Talk less, first look at a picture:

From the above figure, we can see a few things:

1) The browser will parse three things:

    • One is html/svg/xhtml, in fact, Webkit has three C + + classes that correspond to these three types of documents. Parsing these three types of files produces a DOM Tree.
    • CSS, parsing CSS will produce a CSS rule tree.
    • Javascript, scripts, mainly manipulate DOM tree and CSS Rule tree through the DOM API and the CSSOM API.

2) After parsing is complete, the browser engine constructs the Rendering tree through DOM tree and CSS Rule tree. Attention:

    • Rendering tree rendering trees are not the same as DOM trees, because something like a Header or a display:none doesn't have to be placed in the rendering tree.
    • The CSS rule Tree is primarily designed to complete the match and attach the CSS rule to each Element on the Rendering tree. This is the DOM node. The so-called Frame.
    • Then, calculate the position of each Frame (that is, each Element), which is called the layout and reflow process.

3) Finally by invoking the operating system Native GUI API drawing.

  DOM parsing

The DOM Tree of HTML is parsed as follows:

The above HTML will parse into this:

Here's another case with an SVG tag.

  CSS parsing

CSS parsing is probably the following (the following is mainly said Gecko is the play of Firefox), assuming we have the following HTML document:

<doc><title>a few Quotes</title><para>franklin said that <quote> ' a penny saved is a penny E arned. " </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:

And then our CSS document is this:

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

So our CSS Rule Tree would look like this:

Note that the 4th rule in the diagram appears two times, one independent, and one at the sub-node of Rule 3. So, as we can see, building a CSS Rule tree requires a comparison with DOM tree. CSS matching DOM Tree is mainly from right to left parsing CSS Selector, many people think this thing will be faster, in fact, not necessarily. The key is also see our CSS Selector how to write.

  Note: CSS matching HTML elements is a fairly complex and performance issue. So, you will be in n many places to see a lot of people tell you, DOM tree to small, CSS as far as possible with the ID and class, do not cascade down the transition, ...

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

So, Firefox basically generates CSS Rule tree through CSS parsing, then, by creating a style context tree over the DOM, then Firefox passes the style context tree and its Render T The Ree (Frame tree) is connected, it's done. Note: The Render Tree will remove some invisible nodes. and the so-called Frame in Firefox is a DOM node, don't be fooled by its name .

Note: Webkit is not like Firefox to use two trees to do this, Webkit also has a style object, it directly to the style object exists in the corresponding DOM node.

  Rendering

The process of rendering is basically the following (four steps in yellow):

    1. Calculating CSS Styles
    2. Building the Render Tree
    3. layout– positioning coordinates and size, whether line wrapping, various position, overflow, z-index properties ...
    4. Officially open the painting

Note: There are a lot of connectors in the process, which means that Javascript dynamically modifies DOM attributes or CSS properties to cause re-Layout, and some of the changes are not those that refer to the sky, such as the modified CSS rule not being matched to, etc.

It is important to say two concepts, one is Reflow and the other is Repaint. These two are not the same thing.

    • repaint--part of the screen should be redrawn, such as the background color of a CSS has changed. However, the geometric dimensions of the elements do not change.
    • reflow--means that the geometry of the component has changed, and we need to re-verify and calculate the Render Tree. is part or all of the Render Tree has changed. This is Reflow, or Layout. (the HTML uses the flow based layout, which is the streaming layouts, so if the geometry of a component changes and needs to be re-laid,it will be called reflow) Reflow will open from the root frame of

Here's a video of Layout/reflow when you open Wikipedia (Note: HTML will also do a reflow at initialization time, called intial reflow), you can feel:

The cost of Reflow is much higher than the cost of Repaint. Each node in the DOM Tree has a reflow method, and a node's reflow is likely to lead to sub-nodes and even reflow of the parent and sibling nodes. There may be nothing on some high-performance computers, but if reflow occurs on a mobile phone, the process is very painful and draining.

Therefore, the following actions are very likely to be cost-efficient.

    • When you add, delete, and modify DOM nodes, it causes Reflow or Repaint.
    • When you move the DOM's position, or make an animation.
    • When you change the CSS style.
    • When you Resize the window (there is no problem with the mobile side), or when scrolling.
    • When you modify the default font for a Web page.

Note: Display:none will trigger Reflow, and Visibility:hidden will only trigger repaint, as no location changes are found.

Say two more things about scrolling, generally speaking, if the scrolling screen, all the pixels on our page will follow the scroll, then the performance is not a problem, because our graphics card for this kind of full-screen pixels to move down the algorithm is very fast. But if you have a fixed background, or some Element does not follow the scroll, some elment are animated, then this scrolling action will be quite a painful process for the browser. You can see how many of these pages have poor performance when scrolling. Because the scrolling screen may also cause reflow.

Basically, there are several reasons for reflow:

    • Initial. When the page is initialized.
    • Incremental. Some Javascript is manipulating the DOM Tree.
    • Resize. The size of some of its components has changed.
    • Stylechange. If the properties of the CSS have changed.
    • Dirty. Several Incremental reflow occur on the subtree of the same frame.

OK, let's look at an example:

var bstyle = Document.body.style; cachebstyle.padding = "20px"; Reflow, Repaintbstyle.border = "10px solid red";  once again the reflow and Repaintbstyle.color = "blue";//Repaintbstyle.backgroundcolor = "#fad";//Repaintbstyle.fontsize = "2em"; Reflow, repaint//new DOM Element-reflow, Repaintdocument.body.appendChild (document.createTextNode (' dude! '));

Of course, our browser is smart, it will not be like the above, you change the style every time, it reflow or repaint once. In General, the browser will accumulate a batch of such operations, and then do a reflow, which is called asynchronous Reflow or incremental asynchronous reflow. However, in some cases the browser will not do so, such as: Resize window, changed the default font of the page, and so on. For these operations, the browser will be reflow immediately.

But sometimes our script prevents the browser from doing so, for example: if we request some of the following DOM values:

    1. OffsetTop, Offsetleft, offsetwidth, offsetheight
    2. Scrolltop/left/width/height
    3. Clienttop/left/width/height
    4. getComputedStyle () in IE, or Currentstyle

Because, if our program needs these values, then the browser needs to return the latest values, and this will flush out some changes in the style, resulting in frequent reflow/repaint.

  Reduce Reflow/repaint

Here are some of the best practices:

  1) Do not modify the DOM style one by one. Instead, you might as well pre-define the CSS class and then modify the DOM's className.

Badvar left = 10,top = 10;el.style.left = left + "px"; el.style.top  = top  + "px";//Goodel.classname + = "Thecla Ssname ";//Goodel.style.cssText + ="; Left: "+ left +" PX; Top: "+ top +" px; ";

  2) Change the DOM after offline. Such as:

    • Use the DocumentFragment object to manipulate the DOM in memory.
    • First give the DOM to Display:none (once repaint), and then you can change how you want to change it. Change it 100 times and then show him.
    • Clone a DOM node into memory, and then want to change how to change, after the change, and the online exchange.

3) do not place the attribute value of the DOM node in a loop as a variable in the loop. otherwise this will result in a large number of read and write properties of this node.

4) Modify the DOM at a lower level than 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) for animated HTML components using fixed or absoult position, then modifying their CSS is not reflow.

6) Never use the table layout . Because a small minor change can cause the entire table to be re-laid.

In this manner, the user agent can begin into lay out of the table once the entire first row has been received. Cells in subsequent rows does not affect column widths. Any cells that have content that overflows uses the ' overflow ' property to determine whether to clip the overflow content.

Fixed layout, CSS 2.1 specification

This algorithm is inefficient since it requires the user agent to having access to all the content in the table before D Etermining the final layout and may demand more than one pass.

Automatic layout, CSS 2.1 specification

  Several tools and articles

Sometimes, you may find in IE, you do not know what you modified, the result of the CPU went up to 100%, and then after a few seconds repaint/reflow to complete, this kind of things in the era of IE often occurs. So, we need some tools to help us see if there's anything wrong with our code.

    • Google's speedtracer is a very tough job for you to see how expensive your browsing renders are. In fact, both Safari and Chrome can use one of the Timeline in the developer tools.
    • Firefox's Firebug-based Firebug Paint Events plugin is also good.
    • IE you can use an IE extension called dynaTrace.

Finally, don't forget the following articles that 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

    • David Baron's speech: 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 Documentation: http://trac.webkit.org/wiki/WebCoreRendering

Introduction to Browser rendering principles

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.