Reprint: Web front-end optimization

Source: Internet
Author: User

First, HTML optimization to avoid the use of IFRAME

An IFRAME is also called an inline frame, and an HTML document can be embedded in another document. The advantage of using an IFRAME is that the embedded document can be completely independent of its parent document, with this feature we can usually make the browser to simulate multi-threading, it is important to note that the use of an IFRAME does not increase the number of concurrent downloads under the same domain name, the browser connection to the same domain is always shared browser-level connection pool, This is true in all major browsers, even across windows or across tabs. And because of this, the benefits of IFRAME are greatly compromised.

The IFRAME element blocks the triggering of the parent document onload event during page loading, and the developer program typically initializes the UI action when the onload event is triggered. For example, set the focus of the login area. Because the user is accustomed to waiting for this operation, it is important to let the OnLoad event trigger as much as possible so that the user's waiting time becomes shorter. In addition, developers will be bound to some important behavior on the Unload event, but unfortunately in some browsers, only if the OnLoad event triggered after the Unload event can be triggered, if the OnLoad event has not been triggered for a long time, and the user has left the current page, Then the Unload event will never get triggered.
Is there a plan to keep the onload event from being blocked by the IFRAME? There is a simple solution to prevent the onload event from being blocked, using JavaScript to dynamically load the IFRAME element or dynamically set the SRC attribute of the IFRAME:

<iframe id=iframe1 ></iframe> document.getElementById (' iframe1 '). SetAttribute (' src ', ' url ');

However, it is only valid in advanced browsers and is not valid for Internet Explorer 8 and below. In addition, we must know that the IFRAME is one of the most resource-consuming elements in the document, and in Steve Souders's test, load 100 A, DIV, SCRIPT, style, and IFRAME elements in the test page, respectively, in Chrome, Firefox , Internet Explorer, Opera, Safari run 10 times. The result shows that the cost of creating an IFRAME element is an order of magnitude higher than creating other types of DOM elements. All DOM elements in the test are empty, such as loading a large script or style block may take longer than loading some IFRAME elements, but judging from the benchmark results, even an empty IFRAME, the overhead is very expensive, given the high overhead of the IFRAME, we should try to avoid it. Especially for mobile devices, you should avoid using an IFRAME for most of the time, with only a limited amount of CPU and memory.

Avoid empty link properties

An empty Link property means that the src or href attribute of an IMG, link, script, ifrrame element is set, but the property is empty. such as

    1. Internet Explorer 8 and the following browsers only have problems with the IMG type element, IE will resolve the empty address of the IMG to the directory address of the current page address. For example, if the current page address is Http://example.com/dir/page.html,IE, the empty address will be resolved to the http://example.com/dir/address and requested.
    2. Earlier versions of the WebKit kernel browser and Firefox will resolve the empty address to the current page address. If there are multiple empty link attribute elements within the page, the current page server is requested multiple times, increasing the load on the server. This issue is likely to be more serious on iOS and Android mobile browsers than desktop browsers are more aggressive in upgrading the kernel.
    3. Fortunately, when all major browsers are empty from the SRC attribute of the IFRAME, the empty address is resolved to the About:blank address without making additional requests to the server.
Avoid deep-level nesting of nodes

Deep-level nested nodes tend to require more memory footprint when they are initialized, and are slower when traversing nodes, as is the mechanism of the browser building DOM document. For example, the following HTML code:

Through the parsing of the browser HTML parser, the browser will store the entire HTML document structure as a DOM tree structure. The deeper the nesting level of a document node, the deeper the hierarchy of the DOM tree is built.

Reduce HTML Document Size

The most obvious way to increase download speed is to reduce the size of the file, especially the JavaScript and CSS code embedded in the HTML document, which can make the page volume much leaner. In addition to reducing the size of HTML documents you can also take the following methods:

    1. Delete blank lines and comments that have no effect on the result of the HTM document
    2. Avoid table layout
    3. Using HTML5
Explicitly specifying the document character set

Specifying a character set at the beginning of an HTML page helps the browser to begin parsing HTML code immediately. HTML documents are typically parsed into a sequence of strings with character set encoding information that is transmitted over the Internet. The character set encoding is specified in the HTTP response header, or in an HTML tag. The browser parses the encoding into characters that can be displayed on the screen, based on the acquired character set. If the browser does not know the coded character set of the page, it is common to cache the byte stream before executing the script and render the page, then search for a character set that can be parsed, or parse the page code with the default character set, which can lead to unnecessary time consumption. To prevent the browser from spending time searching for the appropriate character set for decoding, it is best to always explicitly specify the page character set in the document.

Explicitly set the width height of the picture

When the browser loads the HTML code of the page, it is sometimes necessary to position the page layout before the picture is downloaded. If the image in the HTML does not specify a size (width and height), or if the size of the code is not the size of the actual picture, then the browser will "backtrack" the image and re-display it after the picture is downloaded, which consumes extra time. Therefore, it is best to specify the size of each image in the page, whether it is in the page HTML tags, or in CSS.

Avoid script blocking loading

When the browser parses the regular script tag, it waits for the script to download and then parse the execution, and the subsequent HTML code can wait. To avoid blocking loading, you should place your footsteps at the end of the document, such as inserting the script tag before the body end tag:

<script src= "Example.js" ></script> </body>
Second, high-performance CSS to avoid the use of @import

There are two ways to load a style file, one is the link element, and the other is CSS 2.1 joins @import. The use of @import in external CSS files can cause the page to add additional latency when loading. While rules allow calling @import in a style to import other CSS, the browser cannot download the styles in parallel, causing the page to add extra round trips. For example, the first CSS file, First.css, contains the following: @import URL ("Second.css"). Then the browser must first download, parse, and execute first.css before discovering and processing the second file SECOND.CSS. The simple workaround is to use the <link> tag instead of @import, such as the following to be able to download CSS files in parallel, thus speeding up the page loading speed:

<link rel="stylesheet" href=""first.css"" /><link rel="stylesheet" href="second.css" />

It is important to note that the CSS file in a page should not be too much, otherwise you should simplify and merge the external CSS files to save the round trip Time (RTT) to increase the page load speed.

Avoid AlphaImageLoader filters

The IE exclusive properties AlphaImageLoader is used to correct the translucent effect of displaying PNG images in the following versions of 7.0. The problem with this filter is that when the browser loads the image it terminates the rendering of the content and freezes the browser. In every element (not just the picture) it will operate once, increasing memory costs, so its problems are manifold. The best way to avoid using alphaimageloader completely is to use the PNG8 format instead, which works well in IE. If you do need to use AlphaImageLoader, use the underscore _filter and make it invalid for users IE7 or later.

Avoid CSS expressions

CSS expressions are a powerful (but dangerous) way of dynamically setting CSS properties. Internet Explorer supports CSS expressions starting with the 5th version. In the following example, a CSS expression can be used to switch the background color at one-hour intervals:

background-color: expression((new Date()).getHours()%2?"#FFFFFF": "#000000" );

As shown above, JavaScript expressions are used in expression. CSS properties are set based on the results of the JavaScript expression calculations. The expression method does not work in other browsers, so it is useful to set it up separately for Internet Explorer in a cross-browser design.

The problem with expressions is that they are calculated more frequently than we think. Not only when the page is displayed and scaled, it is recalculated when the page scrolls, or even when the mouse is moved. Add a counter to the CSS expression to track how often the expression is calculated. Easily move the mouse in the page can be more than 10,000 times the amount of calculation. One way to reduce the number of CSS expression calculations is to use a disposable expression that assigns the result to the specified style property at the first run, and replaces the CSS expression with this property. If the style attribute must change dynamically within the page cycle, using an event handle instead of a CSS expression is a viable option. If you must use CSS expressions, be sure to remember that they are counted thousands of times and may have an impact on the performance of your pages.

Avoid a wildcard selector

The effect of CSS selectors on performance stems from the time it takes for the browser to match selectors and document elements, so the principle of optimizing selectors is to avoid selectors that need to consume more matching time as much as possible. And before that we need to understand the mechanism of CSS selector matching, such as the sub-selector rule for the example:

#header > a {font-weight:blod;}

Most of us are left-to-right reading habits, and may also habitually set the browser to be a left-to-right way to match the rules, because it is assumed that the cost of this rule is not high. Let's pretend that the browser works like this: Find the only element with the header ID, and then apply the style rule to the a element in the immediate child element. We know that there is only one element in the document whose ID is the header, and that it has only a few child nodes of type A, so this CSS selector should be quite efficient.

In fact, the CSS selector is a regular match from right to left, in contrast. After understanding this mechanism, the seemingly efficient selector in the example has a high cost of matching in practice, and the browser must traverse all the a elements in the page and determine whether the ID of its parent element is the header.

If you change the child selector of an example to a descendant selector it will cost more and traverse all the A elements of the page to its ancestor until the root node is traversed.

#header a {font-weight:blod;}

After understanding the mechanism of right-to-left matching of CSS selectors, it is understood that the rightmost rule in the selector often determines the amount of work that the browser will continue to move to the left, and we call the rightmost selection rule the key selector.

The wildcard selector matches each element in the document by using a * compliant representation. The following example rule sets the font size for all elements to 20px:

* { font-size:20px;}

The wildcard selector acts on all elements, such as the wildcard character at the far right of the rule:

.selected * {color: red;}

The browser matches all of the elements in the document up and down to the selected element, until the root node of the document, so its matching overhead is very large, usually up to an order of magnitude higher than the least expensive ID selector, so avoid using a key selector that is a wildcard selector rule.

Avoid single-rule attribute selectors

The following rule sets the link element with the Herf property value equal to "#index" to red, depending on whether the attribute of the element is present or its property value:

.selected [href=”#index”] {color: red;}

However, the matching overhead is very large, the browser matches all the elements first, checks if it has an HREF attribute and the Herf attribute value equals "#index", and then increments the class selected element until the root node of the document. Therefore, you should avoid using a key selector as a rule for a single-rule property selector.

Property selector to avoid class regularization

CSS3 adds a complex property selector that matches the attribute values of an element by means of a class regular expression. Of course, these types of selectors will affect performance, and regular expression matching will be much slower than class-based matching. Most of the cases we should try to avoid using the *=, |=, ^=, $=, and ~= syntax of the attribute selector.

Remove a no match style

There are two benefits to removing a no-match style:

First, delete the useless style can reduce the size of the style file, speed up the download speed of resources;

Second, for browsers, all style rules are parsed and indexed, even if there are no matching rules for the current page. Remove no matching rules, reduce index entries, and speed up browser lookups;

Iii. high-performance JavaScript using event proxies

Sometimes we feel the page is unresponsive because there are too many event handles attached to the DOM tree element and some of the event sentences are frequently triggered. That's why it's a good way to use event proxies. If you have 10 buttons in a div, you just need to attach an event handle to the DIV, instead of adding a handle to each button. When the event bubbles, you can capture the event and determine which event was emitted.

Cache Selector Query Results

A selector query is a costly method. Therefore, you should use selectors as few times as possible, and cache the selected results as much as you want, so that you can reuse them later. For example, the following is a bad way to do this:

jquery (' #top '). Find (' P.classa '); jquery (' #top '). Find (' P.CLASSB ');

A better notation is:

var cached = JQuery (' #top '); Cached.find (' P.classa '); Cached.find (' P.CLASSB ');
Avoid frequent IO operations

The cookie is synchronized with the API of the Localstorage operation, and the cookie and the localstorage are shared between multiple tab pages, and there is a synchronous lock mechanism for simultaneous multi-page operation. It is recommended that cookies or localstorage should be operated as little as possible.

Avoid frequent DOM operations

Accessing DOM elements using JavaScript is slow, so to improve performance, you should:

    1. Caches the elements that have been queried;
    2. After the nodes are updated, they are added to the document tree;
    3. Avoid using JavaScript to modify page layouts;
Using the micro-class library

Often developers use JavaScript libraries such as jquery, Mootools, YUI, Dojo, and so on, but developers often use only a subset of the functionality in the JavaScript class library. For greater performance, you should try to avoid the use of such chatty class libraries, but instead use the micro libraries as needed to aid development.

Reprint: Web front-end optimization

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.