Optimize browser Rendering

Source: Internet
Author: User

Optimize browser Rendering

After resources are downloaded to the client, the browser still needs to load, interpret, and render HTML, CSS, and javasRefer code. 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 the browser
CSS cascade, inheritance, and sorting rules: specify various matching styles for the elements. Execution in Mozilla (possibly in other browsers), CSS search engine uses style rules for each
Element to find the matching style. The engine evaluates each rule from right to left, starting 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 is to delete 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

: Hover

Pseudo 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

: Hover

This will cause performance degradation.

* View the bug report http://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 rule

Body 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 javas for IE.Login onMouseover event (only write the Mouseover event to IE ).

Additional resources

For more details about the efficient CSS rules in Mozilla, see https://developer.mozilla.org/en/writing_efficient_css.

For complete CSS information, see Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) specification. For more information about CSS selectors, see chapter 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 embedded with javas In the CSS attribute values in the CSS declaration.A struct expression. In most cases, they are used for the following purposes:

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

Java SDKCript injection styles are more compact and convenient to provide dynamic styles and Advanced event processing.

Unfortunately, the negative impact of CSS expressions on performance is quite large, because the browser has to re-calculate every time an event is triggered.
Calculate each expression, such as changing the size of a window and moving the mouse. The low performance of CSS expressions is IE.
8. One of the reasons why they are discarded. 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. CSS expressions can be run 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 expression. For a complete list of CSS attributes and IE versions that support them, see CSS attribute indexes in msdn. If you really need to support the old version of IE that is not available with the required CSS attributes, use javasFunctions.

Use javasUpload script style.

If you are using CSS expressions to implement dynamic styles, use pure javasRewrite them makes sense because it improves ie performance and supports the same effect in other browsers. In this example provided by the msdn dynamic attribute 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>

The following is a javasExamples of the equivalence between CSS and CSS are as follows:

<Style> # odiv {position: absolute; Background-color: # cfcfcf ;}</style> <SCRIPT type = "text/javasOther ">
// 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
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 ie versions, you should provide the javasForbidden code: disables 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 ");}

Use the equivalent javas for IE browser versions that do not support this attributeCript replaces the CSS expression with the following content:

<Style> P {max-width: 300px ;}</style> <SCRIPT type = "text/javasOther ">
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. By ensuring that the style sheet is downloaded and parsed first, the browser can gradually render the page

Suggestions

The HTML 4.01 specification (section 12.3) always uses

<Link>

The external style table of the tag is placed in

<Head>

Section. Do not use

@ ImpORT

. Make sure that the style you specified is in the correct 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. Provides image size, browser knowledge
You can even render the page before downloading an image. 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. To prevent reflows

Label 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 (see the optimized image for details .)

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

Be sure to set

The 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.

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.