About Yahoo's 14 military regulations and front-end performance optimization

Source: Internet
Author: User
About Yahoo's 14 military regulations and front-end performance optimization

Heat 4223 times read: | personal: frontend | System: frontend optimization | frontend optimization, Yahoo, and Performance Optimization


  • Enable gzip compression.The idea of Gzip is to first compress the file on the server and then transmit it. This can significantly reduce the file transfer size. After the transfer, the browser will decompress the Compressed Content and execute it again. Currently, all browsers support gzip in a "good" way. Not only can the browser be recognized, but also can be identified by crawlers. In addition, the gzip compression ratio is very large. Generally, the compression ratio is 85%, that is, the K page on the server can be compressed to about 25 K and then sent to the client. For details about the gzip compression principle, refer to the gzip Compression Algorithm in csdn. Yahoo! highlights that all text content should be compressed by gzip: HTML (PHP), JS, CSS, XML, TXT... In this regard, our website is doing a good job. In the past, our homepage was not a, because there were a lot of JS Advertising Code on the homepage. The JS of the website of the ad code owner was not compressed by gzip, which would also drag our website down.
  • Reduces the number of HTTP requests.After you enter the URL and press enter to download content to the client browser, you need to go through 1. domain name resolution 2. Enable TCP Connection
    3. Send a request
    4. Waiting (mainly including network latency and server processing time)
    5. Download Resources
    Reducing HTTP requests has the following advantages:
    (1) reduce the time required for DNS requests.
    Not to mention right or wrong, because in general, reducing the number of HTTP requests can indeed reduce the time required for DNS requests and resolution.
    (2) reduce server pressure.
    This is usually the most widely considered, and it is also the biggest reason I want to explain to others, because each HTTP request consumes server resources, especially some servers that need computing, merging, and other operations, it is not a joke to consume the server's CPU resources. The hard disk can be purchased with money, and the CPU resources are not that cheap.
    (3) Reduce the HTTP request header.
    When we initiate a request to the server, we will carry the cookie and some other information under this domain name in the HTTP header, then, when the server responds to the request, it will also bring back some header information such as cookies. this information is sometimes very large, and affects bandwidth performance in such requests and responses.
  • Undoubtedly, every HTTP request is time-consuming. How can we reduce the number of HTTP requests?
  • How to reduce the number of requests

    1. Merge files
    Merging files is to merge many JS files into one file, and many CSS files into one file. This method should be used by many people and will not be described in detail here,
    Only one merge tool is recommended: Provided by the yuicompressor tool Yahoo. Http://developer.yahoo.com/yui/compressor/

    2. Merge Images
    This uses CSS sprite to display different images by controlling the position of the background image. This technology is also used by everyone, do not make a detailed introduction, it is recommended that 1 online merge pictures of the Website: http://csssprites.com/

    3. Merge JS and CSS into one file.
    The above 1st methods only merge several JS files into one JS file, and several CSS files into one CSS file, how to merge CSS and JS into one file? See my other article:
    Http://www.blogjava.net/BearRui/archive/2010/04/18/combin_css_js.html

    4. Use Image Maps
    Image Maps combines multiple images into one image, uses the <map> tag in HTML to connect to the image, and performs different operations by clicking different areas of the image, image map is easier to use in navigation bar.
    For the use of image map, see: http://www.w3.org/TR/html401/struct/objects.html#h-13.6

    5. data embedded Images
    In this way, the image is encoded and directly embedded into HTML for use to reduce HTTP requests, but this increases the size of the HTML page, and the embedded image cannot be cached.
  • Place the CSS file in the To prevent users from seeing only blank pages in the IE browser at low speed. Although Firefox does not block it, it may need to be re-painted, which may cause page flashes. Therefore, in order to improve the rendering performance of the browser and avoid blank or flickering pages. Put the CSS file in the
  • Use CDN. CDN stands for content delivery network (CDN. The basic idea is to avoid bottlenecks and links on the Internet that may affect data transmission speed and stability, so that content transmission can be faster and more stable.
  • Put the <SCRIPT> label at the bottom. He will present the content first and won't let the user wait too long. This prevents script execution from blocking page downloads. In the process of page loading, when the browser reads the JS execution statement, it will definitely explain it all and then read the following content. If you don't believe it, you can write a javascript endless loop to see if something on the page will come out. Therefore, the last part of the page can effectively reduce the loading time of page elements.
  • Add expire/cache-control header: add an Expires header

    Now more and more images, scripts, CSS, and Flash are embedded into the page. When we access them, we are bound to make many HTTP requests. In fact, we can cache these files by setting the Expires header. Expire uses the header message to specify the cache time of a specific type of file in the browser. Most of the images and Flash files do not need to be modified frequently after they are released. After the files are cached, the browser does not need to download these files from the server but read them directly from the cache, in this way, the page access speed will be greatly accelerated.

  • Avoid using CSS expression expressions.CSS expressions reduce the rendering performance of the browser. When the page is scrolling, moving the mouse, and scaling the page, all elements must be re-computed, greatly reducing the browser's performance.


    8. Place the CSS and JS files externally.This should be done not only in terms of performance optimization, but also in terms of easy code maintenance. Writing CSS and JS on the page can reduce the number of requests twice, but also increase the page size. If CSS and JS are already cached, there will be no additional HTTP requests. Of course, as I mentioned earlier, some special page developers still choose inline CSS and JS files. It also greatly improves the reusability of CSS and JS Code.

    When writing on a page: only one page is used; infrequently accessed; few scripts and styles are used.

    9. Reduce DNS requests:Each computer on the network has an independent IP address. The translation between a domain name and an IP address is called domain name resolution or DNS query. A dns resolution process consumes 20-20 ms. the browser will not download anything under the domain name until the DNS query is complete. Therefore, reducing the DNS query time can speed up page loading. Yahoo recommends that the number of domain names on a page be limited to 2 to 4.

    The default DNS Cache Time of IE is 30 min; Firefox is 60 s; Chrome is 60 s;



    10. Compress JavaScript and CSS. Remove unnecessary characters, comments, and spaces. Obviously, the size of JavaScript and CSS is reduced by the number of page bytes. Page loading speed is naturally fast when the capacity is small. In addition to reducing the volume, compression can also provide some protection. We have done a good job. Common compression tools include jsmin and Yui compressor. For example, http://dean.edwards.name/packer/provides us with a very convenient on-line compression tool.


    11. Avoid redirection. The original request is redirected to another request.









    14. Use Ajax cache.


In addition to the preceding fourteen Yahoo military rules, you can also use the following three optimization suggestions:
High-performance html
I. Avoid using IFRAME
IFRAME is also called an inline frame. You can embed an HTML document into another HTML document.
The advantage of IFRAME is that the embedded document is independent of the parent document, which usually enables the browser to simulate multithreading. Disadvantages:
① Although IFRAME can simulate multithreading, the number of concurrent downloads to the same domain name in mainstream browsers remains unchanged. the browser's connections to the same domain name always share the browser-level connection pool,
Even for webpages with the same domain name in different windows or tabs.
② When the page is loaded, IFRAME will block the trigger of the onload event of the parent document. In addition, some browsers can trigger the onUnload Event only after the onload event is triggered.
Therefore, the onUnload Event will not be triggered when the user leaves the page without triggering the onload event for a long time.
※Not compatible with IE6 ~ 8. Solution: use JavaScript to dynamically load the IFRAME element or set its src attribute dynamically.
  1. <IFRAME id = IFR> </iframe>
  2. Document. getelementbyid ('ifr'). setattribute ('src', 'url ');
Copy code


③ IFRAME is one of the most resource-consuming elements in the document, and the overhead of an empty IFRAME is expensive. [Tested by Steve Souders]

Ii. Avoid empty Connection Properties
Null join: the SRC or href attribute value of the IMG, Link, script, and IFRAME elements is null. (For example, src = "")
After an empty connection is set, the browser still sends the request according to the default rule:
① IE6 ~ In 8, only the IMG element has a problem: IE will resolve the empty address of IMG to the directory address of the current page address and request.
For example, if the current webpage address is http://aaa.com/bb/c.html, the imgaddress will be merged to http://aaa.com/bb
② Earlier versions of WebKit and Firefox will resolve empty connections to the address of the current page. This problem is serious in iOS and Android.
If the page has multiple null connection attribute elements, the number of server requests is increased.
③ Fortunately, when the src attribute value of IFRAME is null in mainstream browsers, it will be resolved to the about: blank address without sending additional requests.

3. Avoid deep node nesting
Nodes with deeper hierarchies occupy more memory during initialization.
The HTML Parser in the browser stores the structure of the entire HTML document as a DOM tree structure. The deeper the node nesting hierarchy, the deeper the DOM book hierarchy.

Iv. Reduce HTML document size
① Delete blank space lines and comments that have no effect on execution results;
② Avoid table layout;
③ Use HTML5;

5. Explicitly specify the document Character Set
Specifying a character set when opening an HTML page helps the browser to parse HTML code immediately.
HTML documents are usually parsed into a series of character set encoding strings that are transmitted over the Internet.
Character Set encoding is specified in the HTTP response header or in the HTML Tag. The browser uses the specified character set to encode and parse the code into realistic characters on the screen.
If the browser cannot know the encoding Character Set of the page, it will cache the byte stream before executing the script and rendering the page, and then search for the character set that can be parsed or parse it with the default character set.

6. Set the image width and height.
Sometimes you need to locate the page layout before loading the page.
If the size of the image on the page is not specified, or the size does not match the actual image size, the browser will "backtrack" the image and display it again after the image is downloaded, thus wasting time.
Therefore, it is best to specify the size (intra-row style or CSS style) for the page image ).
Copy code


7. Avoid script Blocking
When parsing regular script tags, the browser will wait for the script to be downloaded before parsing and executing the script. Then, the HTML code can only wait.
Therefore, the script should be placed at the end of the document:
  1. <SCRIPT src = "example. js"> </SCRIPT>
  2. </Body>
Copy code


High-performance CSS
I. Avoid using @ import
@ Import added by css2.1 will add additional latency during page loading.
Because the browser cannot download the style in parallel, it will add additional round-trip time on the page. However, the <link> can be used for parallel download, but it may be multiple requests.
Ii. Avoid alphaimageloader Filters
This filter can solve IE6, that is, display the translucent effect of a PNG Image in the following version, but it will terminate the rendering of the content when loading the image and freeze the browser.
Each element (not just an image) is computed once to add memory expenses.
The png8 format should be used, or the underscore (_ filter) should be used only for ie6.
3. Avoid CSS expressions
CSS expressions are the method for setting dynamic CSS attributes, that is, emphasizing and dangerous. Ie5 is supported and is unique to IE.

// Implements switching the background color copy code once every hour
The disadvantage of CSS expressions is that the technology frequency is extremely high. The display, zoom, scroll, or move the mouse on the page will be recalculated once. The amount of work that can be moved is more than one million times.
① Using a one-time expression can reduce the number of computations. In the first run, the result is assigned to the specified style attribute, and this attribute is used to replace the CSS expression.
② If the style attribute must be dynamically changed within the page cycle, it is feasible to use the time handle instead of the CSS expression.

4. Avoid wildcard Selector
The principle of optimizing the selector is to reduce the matching time. The matching mechanism of CSS selector is: regulate matching from right to left!
# Header> A {font-weight: blod ;}
The rule above is that the browser traverses all the elements on the page and determines whether the ID of the parent element is the header.
# Header {...}
The overhead of the descendant selector is greater. After traversing all the elements of the page, the Child selector needs to traverse up until the root node.
It can be seen that the rightmost regulation of selector usually determines the workload of moving to the left. Therefore, the rightmost selection rule is called a key selector.
. Selected *{...}
After all the elements are matched, they are matched up until the root node. Usually higher than the ID selector with the minimum overhead ·~ Three orders of magnitude.

5. Avoid attribute selector of a single rule
. Selected [href = '# Index'] {...}
The browser first matches all elements, checks whether they have the href attribute and the value is "# Index", and then matches the elements whose class is selected respectively.
Therefore, you should avoid using the key selector as the single rule attribute selector rule.

6. Avoid regular attribute Selector
Css3 adds a complex attribute selector and matches the regular expression of the class. However, these type selectors are much slower than category-based matching.

7. Remove unmatched styles
① Deleting useless styles can reduce the size of style files and speed up loading.
② For browsers, all style rules will be indexed after resolution, even if there is no matching rule on the current page! Therefore, remove unmatched rules, reduce index items, and speed up browser search.

High-performance Javascript
I. Use event proxy
When too many time handles are frequently triggered, the page response will be slow.
If a div has 10 buttons, you only need to attach an event handle to the DIV once, instead of adding a handle to each button.
Events are captured at the time of bubbling and the event is triggered at the time of determination. [Element that triggers the event = eV. srcelement? Ev. srcelement: ev.tar get ;]
Ii. cache selector query results
Reduce the number of selector queries and cache the selected results as much as possible to facilitate future reuse.


  1. Jquery ('# Top'). Find ('p. classa ');
  2. ...
  3. Jquery ('# Top'). Find ('p. classb ');
Copy code
// Use the following method to reduce the overhead
  1. VaR cached = jquery ('# top ');
  2. Cached. Find ('p. classa ');
  3. ...
  4. Cached. Find ('p. classb ');
Copy code


Iii. Avoid frequent Io operations
Reduce cookie or localstorage operations because the APIs for which operations are performed are synchronized, and they are shared among multiple tab pages.
When multiple pages simultaneously operate on cookies and localstorage, the synchronization lock mechanism will exist.

4. Avoid frequent Dom operations
Javascript is slow to access DOM elements, so you should:
① Cache the queried elements;
② After offline node updates, add them to the document tree;
③ Avoid using JavaScript to modify the page layout.

5. Use a micro-class library
Avoid using large and complete class libraries as much as possible. Instead, use the micro class libraries as needed to assist development. Http://www.w3cfuns.com/blog-5434413-5399486.html

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.