To optimize browser Rendering

Source: Internet
Author: User
ArticleDirectory
    • Optimize browser Rendering

Address: http://www.99css.com/archives/275

Bigbi of ISD webteam (Twitter: @ tc_bryanzhang) sacrificed a lot of XX time to translate optimize browser rendering in the page speed series because its blog is still being rebuilt, so I will repost it here. The full text is as follows:

Optimize browser Rendering

After resources are downloaded to the client, the browser still needs to load, interpret, and render HTML, CSS, and JavaScriptCode. You can simply orchestrate your code and pages based on the features of your existing browser to improve client performance.

    1. Use an efficient CSS Selector
    2. Avoid CSS expressions
    3. Place the style sheet on the top of the page
    4. Specify image size

Use an efficient CSS Selector

Overview

Avoid inefficient key selectors that match a large number of elements to accelerate page rendering.

Details

When the browser parses HTML, it first constructs an internal file tree to represent all the displayed elements. Then, based on the standard CSS cascade, inheritance, and sorting rules, the browser specifies various matching patterns for the elements. Execution in Mozilla (possibly in other browsers). CSS search engines use style rules to find matching styles for each element. The engine evaluates each rule from right to left, starts from the rightmost selector (called "key" [Key]), and moves each selector, until a matching or discarded rule is found. ("Selector" is the document element of the application rule .)

Based on this principle, the fewer rules the engine wants to evaluate, the better. Therefore, an important step to improve rendering performance isDelete unused CSS. Then, for pages that contain a large number of elements and/or CSS rules, optimizing the definition of the rule itself can improve the performance. The key to optimizing rules is to define rules as much as possible and avoid unnecessary duplication, so that style engines can quickly find matching rules without having to spend time searching unsuitable rules.

The following rules are considered inefficient:

Descendant selector rules

For example:

Rules for using the wildcard selector as a key

 
Body * {...}. Hide-scrollbars *{...}

Tag selector as a key rule

 
Ul Li a {...} # footer H3 {...} * html # atticpromo ul Li {...}

The descendant selector is inefficient, because for each element that matches the key, the browser must traverse the DOM tree and evaluate each ancestor element until a matching or reaching the root element is found. The less specific the key, the larger the number of nodes to be evaluated.

Rules of child selector and adjacent Selector

For example:

Rules for using the wildcard selector as a key

 
Body> * {...}. Hide-scrollbars> *{...}

Tag selector as a key rule

 
Ul> LI> A {...} # footer> H3 {...}

Child selectors and adjacent selectors are inefficient because the browser must evaluate another node for each matching element. This will double the consumption of each sub-selector in the rule. Similarly, the less specific the key, the larger the number of nodes to be evaluated. Even so, although it is equally inefficient, they are still desirable in terms of performance compared to descendant selectors.

Rules with additional Modifiers

For example:

 
Ul # top_blue_nav {...} form # userlogin {...}

Id selection is a unique definition. Adding tags or classes only adds additional information that causes unnecessary evaluations.

Apply non-link elements: HoverPseudo selector rules

For example:

 
H3: hover {...}. Foo: hover {...} # FOO: hover {...} Div. FAA: hover {...}

On non-linked elements: the hover pseudo selector * slows down IE 7 and IE 8 in some cases. When the page does not have a strict doctype, IE 7 and IE 8 will ignore any elements except links: Hover. When the page has a strict doctype: HoverThis will cause performance degradation.

* View the bug reportHttp://connect.microsoft.com/IE/feedback/ViewFeedback.aspx? Feedbackid = 391387.

Suggestions

Avoid wildcard selector.

The element can inherit the style of the ancestor, or use a class to apply the style to multiple elements.

Make your rules as specific as possible.

Use the class and ID selector instead of the label selector whenever possible.

Delete unnecessary modifiers.

These modifiers are redundant:

The ID selector is limited by the class selector and/or the label selector.

The class selector is restricted by the label selector (when a class is only used for a label, it is a good design practice in any case ).

Avoid using descendant selectors, especially those that specify excessive ancestor.

For example, this ruleBody ul Li {...}An extra body selector is specified, because all elements are descendants of the Body Tag.

Use the class selector instead of the descendant selector.

For example, if you want to have two styles of ordered list items and unordered list items, instead of using two rules:

 
Ul Li {color: Blue;} ol Li {color: red ;}

You can encode a style into two class names and use them in rules. For example:

. Unordered-list-item {color: Blue;}. Ordered-list-item {color: red ;}

If you must use the descendant selector, try to use the child selector. This requires at least one additional node to be evaluated, not all nodes in the middle until the ancestor.

Avoid applying non-linked elements in IE: hover.

If you apply hover to non-linked elements, test it in IE7 and IE8 and make sure the page is available. If you find that hover causes performance problems, consider using JavaScript onmouseover events (only write Mouseover events for IE) for IE ).

Additional resources

For more details about the efficient CSS rules in Mozilla, seeHttps://developer.mozilla.org/en/Writing_Efficient_CSS.

For complete CSS information, seeCascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. For more information about CSS selectors, seeChapter 5.

Back to Top

Avoid CSS expressions

Overview

CSS expressions reduce the rendering performance of the browser. replacing them with other schemes will improve the rendering performance of the IE browser.

Note:This section best practices only apply to Internet Explorer 5 to 7. They support CSS expressions. Internet Explorer 8 does not support CSS expressions, which are not supported by other browsers.

Details

As a way to dynamically change document attributes to respond to various events, Internet Explorer 5 introduces CSS expressions or "dynamic attributes ". They are composed of JavaScript expressions embedded in the CSS attribute values in the CSS declaration. In most cases, they are used for the following purposes:

Simulate standard CSS attributes supported by other browsers but not supported by IE.

It provides dynamic styles and Advanced event processing in a more compact and convenient way than writing a comprehensive javascript injection style.

Unfortunately, CSS expressions have a considerable negative impact on performance, because every time an event is triggered, the browser recalculates each expression, for example, changing the size of a window and moving the mouse. The low performance of CSS expressions is one of the reasons why IE 8 discards them. If you use CSS expressions on a webpage, you should do everything you can to eliminate them and use other methods to achieve the same functionality.

Suggestions

Use standard CSS attributes whenever possible.

IE 8 is highly compatible with standard CSS. IE 8 supports running CSS expressions only in "compatible" mode, but not in "standard" mode. If you do not need to be backward compatible with the earlier version of IE, you should convert it to the standard CSS attribute to replace all the corresponding CSS expressions. For a complete list of CSS attributes and IE versions that support them, see the CSSAttribute Index. If you really need to support the old IE browser that requires CSS attributes to be unavailable, use JavaScript to implement equivalent functions.

Use the Javascript script style.

If you are using CSS expressions to implement dynamic styles, it is very meaningful to rewrite them with pure JavaScript, because this will not only improve ie performance, but also get support for the same effect in other browsers. In thisDynamic attributesIn the example provided by the page, the following CSS expression is used to center an HTML block element in the browser, and the size of the element can be changed at runtime, each time you adjust the window size, you can reposition it in the browser center:

 
<Div id = "odiv" style = "background-color: # cfcfcf; position: absolute; left: expression (document. body. clientwidth/2-odiv.offsetwidth/2); top: expression (document. body. clientheight/2-odiv.offsetheight/2) "> example Div </div>

Below is an equivalent example of using JavaScript and standard CSS:

<Style> # odiv {position: absolute; Background-color: # cfcfcf ;} </style> <SCRIPT type = "text/JavaScript"> // check for browser support of event handling capability if (window. addeventlistener) {window. addeventlistener ("LOAD", centerdiv, false); window. addeventlistener ("resize", centerdiv, false);} else if (window. attachevent) {window. attachevent ("onLoad", centerdiv); window. attachevent ("onresize", centerdiv);} else {window. onload = centerdiv; window. resize = centerdiv;} function centerdiv () {var mydiv = document. getelementbyid ("odiv"); var mybody = document. body; var bodywidth = mybody. offsetwidth; // needed for Firefox, which doesn't support offsetheight var bodyheight; If (mybody. scrollheight) bodyheight = mybody. scrollheight; else bodyheight = mybody. offsetheight; var divwidth = mydiv. offsetwidth; If (mydiv. scrollheight) var divheight = mydiv. scrollheight; else var divheight = mydiv. offsetheight; mydiv. style. top = (bodyheight-divheight)/2; mydiv. style. left = (bodywidth-divwidth)/2 ;}</SCRIPT>

If you use CSS expressions to simulate CSS attributes that are unavailable in earlier versions of IE, you should provide JavaScript code for version testing and disable CSS expressions for browsers that support CSS. For example, the max-width attribute forces Text wrap within a certain number of pixels, which is not supported before IE 7. The following CSS expression provides this function for IE 5 and 6 as a solution:

 
P {width: expression (document. Body. clientwidth> 600? "600px": "Auto ");}

To replace CSS expressions with equivalent Javascript in IE browser versions that do not support this attribute, you can use something similar to the following:

 
<Style> P {max-width: 300px ;}</style> <SCRIPT type = "text/JavaScript"> If (navigator. appname = "Microsoft Internet Explorer") & (parseint (navigator. appversion) <7) window. attachevent ("onresize", setmaxwidth); function setmaxwidth () {var paragraphs = document. getelementsbytagname ("p"); For (VAR I = 0; I <paragraphs. length; I ++) paragraphs [I]. style. width = (document. body. clientwidth> 300? "300px": "Auto"); </SCRIPT>

Back to Top

Place the style in the header of the page

Overview

Inline style blocks and<Link>Element from page<Body>Move to page<Head>To improve rendering performance.

Details

In the HTML file<Body>Specifying external style sheets and inline style blocks in may adversely affect the rendering performance of the browser. The browser blocks rendering of the webpage until all external style sheets are downloaded. (Use<Style>The specified inline style block may cause reflows and page beating. Therefore, place external style sheets and inline style blocks on<Head>Is very important. Ensure that the style sheetFirstDownload and parse first, allowing the browser to gradually render the page

Suggestions

HTML 4.01 specification (Section 12.3), Always use<Link>The external style table of the tag is placed in<Head>Section. Do not use@ Import. Make sure that the style you specified hasCorrect order.

Set<Style>Block placement<Head>Section.

Back to Top

Specify image size

Overview

Specifying the width and height for all images on the page can eliminate unnecessary reflows and redraw the page [repaints] to make page rendering faster.

Details

When a browser sketch a page, it needs to be able to flow, such as a replaceable element. The image size is provided, and the browser knows that irreplaceable elements nearby can even be used to render the page before the image is downloaded. If no image size is specified or the specified size does not match the actual size of the image, the browser will need to reflows and redraw the page once the image is downloaded. To prevent reflowsLabel or specify the width and height for all images in CSS.

Suggestions

Specify the size of the image.

Do not use non-original image size to scale the image. If the actual size of an image file is 60x60 pixels, do not set the size to 30x30 pixels in HTML or CSS. If the image requires a small size, set it to a consistent size in the image editing software (for details, seeOptimize images.)

Be sure to specify the size of the image or its block-level parent Element

Be sure to setThe size of the element itself, or its block-level parent element. If the parent element is not a block-level element, the size is ignored. Do not set the size on the ancestor element of a non-Recent parent element.

Back to Top

Note: In order to re-render part or the whole page, the process of recalculating the page element location and geometric structure is called reflow.

-------- 2011-3-18 supplement ----------

Google later made changes to this document. For some new translations, see supplement to optimized browser rendering]

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.