[Reprint] Website performance optimization of JavaScript and css--website front-end performance optimization

Source: Internet
Author: User
Tags blank page website performance



Have seen the Yahoo team wrote an article on the performance optimization of the site, the article is about 2010 years written, although a bit old, but many aspects are still very useful reference. As for the performance optimizations of CSS, he mentions the following points:


CSS Performance Optimizations


1. Place the style sheet on top



Placing the stylesheet inside the < head/> of the document seems to speed up the download of the page. This is because putting the stylesheet into < head/> will cause the page to load in a step.



Performance-focused front-end servers tend to want pages to load in an orderly fashion. At the same time, we want the browser to display the content that has been received as much as possible. This is especially important for pages with more content and for users with slower speeds. Returning visual feedback to the user, such as process pointers, has been well researched and formed formal documentation. In our research, the HTML page is the process pointer. When the browser loads the file header, navigation bar, top logo and so on, it can be used as a visual feedback for users waiting for the page to load. This improves the user experience in general.



The problem with putting stylesheets at the bottom of the document is that in many browsers, including Internet Explorer, this aborts the ordered rendering of content. The browser aborts rendering to avoid redrawing the page elements caused by style changes. The user has to face a blank page.



The HTML specification clearly states that the style sheet is to be included in the < head/> area of the page: "and < a/> different,< link/> can only appear in the < head/> area of the document, although it can be used more than once." Whether it is causing white screen or not styling content is not worth trying. The best solution is to download your stylesheet in document < head/> Nega According to the HTML specification.



2. Avoid using CSS expressions (expression)



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.



3. Using external JavaScript and CSS



Many performance rules are about how to handle external files. However, before you take these steps you may ask a more basic question: should JavaScript and CSS be placed in external files or placed within the page itself?



Using external files in real-world applications can improve page speed because both JavaScript and CSS files can generate caches in the browser. JavaScript and CSS built into HTML documents are re-downloaded in each request with an HTML document. This reduces the number of HTTP requests, but increases the size of the HTML document. On the other hand, if the JavaScript and CSS in the external file are cached by the browser, you can reduce the size of the HTML document without increasing the number of HTTP requests.



The key issue is that the frequency of external JavaScript and CSS file caches is related to the number of requests for HTML documents. Although there are some difficulties, there are still some indicators that can measure it. If a user in a session browses to multiple pages in your site, and the same scripts and stylesheets are reused on those pages, caching external files can be a greater benefit.



For home pages with larger views, there is a technology that balances the benefits of reducing HTTP requests from built-in code with caching by using external files. One of them is the built-in JavaScript and CSS on the homepage, but when the page is downloaded, the external files are downloaded dynamically, and when they are used in the sub-pages, they are cached in the browser.



4. Cut JavaScript and CSS



Streamlining means reducing the file size by removing unnecessary characters from the code to save download time. All comments, unwanted whitespace characters (spaces, line breaks, tab indents) are removed when the code is subtracted. In JavaScript, the volume of files that need to be downloaded is reduced, which saves response time. The most extensive two tools currently used in thin JavaScript are jsmin and Yui Compressor. YUI compressor can also be used to streamline CSS. One of my previous articles on front-end deployment, the Ant+yui Compressor address is: The http://www.haorooms.com/post/ant_yuicom gadget also has the Ant usage:/http www.haorooms.com/tools/ant_book/



Obfuscation is another method that can be used for source code optimization. This approach is more complex and confusing than streamlining and is more prone to problems. In a survey of the top 10 U.S. websites, streamlining can also reduce the volume of the original code by 21%, while confusion can reach 25%. Although obfuscation can be a better way to reduce code, the risk of streamlining for JavaScript is even smaller.



In addition to cutting out external scripts and stylesheet files,< script> and < style> blocks of code can and should be trimmed. Even if you compress scripts and stylesheets with gzip, streamlining these files can save more than 5% of your space. Because of the increased functionality and volume of JavaScript and CSS, code reduction will benefit.



5, replace @import



The previous best implementations mentioned that CSS should be placed at the top to facilitate an orderly loading rendering.



In IE, the bottom of the page @import and use < link> function is the same, so it is best not to use it.



6. Avoid using 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.


JavaScript Performance Optimizations


1. Place the script at the bottom of the page



The problem with scripting is that it blocks parallel downloads of pages. The http/1.1 specification recommends that there be no more than two concurrent downloads for each host name in the browser. If your picture is placed on multiple host names, you can download more than 2 files at a time in each parallel download. However, when the script is downloaded, the browser does not download other files at the same time, even if the host name is different.



In some cases it may not be easy to move the script to the bottom of the page. For example, if the script uses document.write to insert the page content, it cannot be moved down. There may also be a scope problem here. In many cases, this problem will be encountered.



A frequently used workaround is to use deferred scripting. The Defer property indicates that the script does not contain document.write, which tells the browser to continue displaying. Unfortunately, Firefox does not support the defer property. In Internet Explorer, scripts can be delayed but not as expected. If the script can be delayed, it can be moved to the bottom of the page. This will make your page load a little faster.



2. Using external JavaScript and CSS



Ditto, the CSS is written, I have listed in the previous Article CDN, you can call the external. CDN Public Library: Http://www.haorooms.com/post/cdn_all



3. Cut JavaScript and CSS



Ditto, the CSS is written in



4. Eliminate duplicate scripts



Repeatedly referencing JavaScript files on the same page can affect the performance of the page. You might think this is a rare situation. Surveys of the top 10 U.S. websites show that two of them have duplicate reference scripts. There are two main factors that cause a script to be repeatedly referenced by a strange phenomenon: the size of the team and the number of scripts. If this is the case, repeating the script causes unnecessary HTTP requests and useless JavaScript operations, which reduces site performance.



Unnecessary HTTP requests are generated in Internet Explorer, but not in Firefox. In Internet Explorer, if a script is referenced two times and it is not cacheable, it generates two HTTP requests during the page load process. Instant scripts can be cached, and additional HTTP requests are generated when the user reloads the page.



In addition to adding additional HTTP requests, multiple operations scripts can be a waste of time. In Internet Explorer and in Firefox, regardless of whether the script is cacheable, there is a problem with repetitive arithmetic javascript.



One way to avoid occasional two references to the same script is to use the Script management module to reference the script in the template. The most common way to reference a script using the < script/> tag in an HTML page is:


<script type="text/javascript" src="menu_1.0.17.js"></script>


In PHP you can override this by creating a method named Insertscript:


<?php insertScript("menu.js") ?>


To prevent multiple references to scripts, this method should also use other mechanisms to process scripts, such as checking the owning directory and adding a version number to the script file name for the expire file first class.



5. Reduced DOM Access



Using JavaScript to access DOM elements is slow, so in order to get more of the supposed pages, you should:



Cache the relevant elements that have been accessed



Add them to the document tree after you update the nodes below the line



Avoid using JavaScript to modify page layouts



6. Develop Intelligent event handlers



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 using the event delegation is a good way to do that. 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.



You also don't have to wait for the OnLoad event to operate the DOM tree. All you need to do is wait for the element you want to access in the tree structure to appear. You don't have to wait for all the images to load.


How to load js,js where to put the research


Blocking download of external JS



All browsers in the download JS, will block all other activities, such as the download of other resources, content rendering and so on. Until JS is downloaded, parsed, executed, and then continues to download additional resources and render the content in parallel.



Some people will ask: Why JS can not be like CSS, image parallel download? Here is a brief introduction to the principle of the browser construction page, when the browser receives the HTML document from the server, and the HTML in memory to the DOM tree, in the process of conversion if you find that a node (nodes) referenced CSS or IMAGE, will send 1 more requests to request the CSS or image, and then continue to perform the following conversion, without waiting for the request to return, when the request returned, only need to put the returned content in the DOM tree corresponding to the location of OK. But when JS is quoted, the browser sends 1 JS request and waits for the request to return. Because the browser needs 1 stable DOM tree structure, and JS is very likely to have code directly changed the DOM tree structure, such as using document.write or appendchild, Even the direct use of the location.href to jump, the browser in order to prevent the occurrence of JS modified DOM tree, the need to rebuild the DOM tree, so it will block the other download and rendering.



Blocking download diagram: Is the time to visit the Blogjava home page waterfall, you can see that the beginning of the 2 images are parallel download, and the back of the 2 js are blocked download (a 1 download).






Blocking download with JS embedded



Embedded JS refers to the JS code that is written directly in the HTML document. It said that the reference to the external JS will block the subsequent resource download and subsequent content rendering, which embedded JS will be how to block, see the following column 2 code:

** Code 1: **

<div>
         <ul>
             <li> blogjava </ li>
             <li> CSDN </ li>
             <li> haorooms blog </ li>
             <li> ABC </ li>
             <li> AAA </ li>
         <ul>
     </ div>
     <script type = "text / javascript">
        // Loop for 5 seconds
         var n = Number (new Date ());
     var n2 = Number (new Date ());
    while ((n2-n) <(6 * 1000)) {
       n2 = Number (new Date ());
     }
     </ script>
   <div>
         <ul>
             <li> MSN </ li>
             <li> GOOGLE </ li>
             <li> YAHOO </ li>
         <ul>
</ div>
After running, you will find that in Code 1, the page is blank in the first 5 seconds, and all pages are displayed after 5 seconds. In Code 2, blogjava, csdn, etc. are displayed first in the first 5 seconds, and MSN is displayed after 5 seconds.

It can be seen that the embedded JS will block the presentation of all content, while the external JS will only block the display of the subsequent content. Both methods will block the download of subsequent resources.

The problem of CSS blocking loading caused by embedding JS

How can CSS block loading? CSS can be downloaded in parallel, under what circumstances will there be blocking loading (in the test observation, CSS is blocking loading under IE6, the following test is performed under non-IE6):

Code 1 (For effect, CSS of a foreign server is selected here):

<html xmlns = "http://www.w3.org/1999/xhtml">
         <head>
           <title> js test </ title>
           <meta http-equiv = "Content-Type" content = "text / html; charset = UTF-8" />
           <link type = "text / css" rel = "stylesheet" href = "http://69.64.92.205/Css/Home3.css" />
         </ head>
         <body>
             <img src = "http://www.haorooms.com/images/logo.gif" /> <br />
              <img src = "http://www.haorooms.com/images/csdnindex_piclogo.gif" />
         </ body>
</ html>
Time waterfall chart:

Code 2 (only 1 empty embedded JS is added):

<head>
     <title> js test </ title>
     <meta http-equiv = "Content-Type" content = "text / html; charset = UTF-8" />
   <link type = "text / css" rel = "stylesheet" href = "http://69.64.92.205/Css/Home3.css" />
   <script type = "text / javascript">
         function a () {}
   </ script>
</ head>
<body>
         <img src = "http://www.haorooms.com/images/logo.gif" /> <br />
         <img src = "http://www.haorooms.com/images/csdnindex_piclogo.gif" />
</ body>
Time waterfall chart:

As can be seen from the time waterfall chart, in Code 2, the CSS and the image are not downloaded in parallel, but wait for the CSS to be downloaded before downloading the next 2 images in parallel. There will be a situation that blocks downloading of resources behind.

Some people may ask, why not talk about embedded JS blocking the resources behind, but CSS blocking? Think about what we are using now is an empty function, parsing this empty function 1ms is enough, and the next two pictures are waiting to download after CSS download 1.3s. You can also try to put the embedded JS in front of the CSS, there will be no blocking.

The root cause: Because the browser maintains the order of css and js in the HTML, the style sheet must be loaded and parsed before the embedded JS is executed. The embedded JS will block the subsequent resource loading, so the above CSS will block the download.

Where should the embedded JS be placed

1. At the bottom, although it will still block all presentations at the bottom, it will not block resource downloads.

2. If the embedded JS is placed in the head, please place the embedded JS in front of the CSS.

3. Use defer

4. Don't call long-running functions in embedded JS. If you must use them, you can call them with setTimeout. About settimeout, I wrote in an earlier article, please see: http: //www.haorooms .com / post / js_setTimeout

 

http://www.haorooms.com/post/web_xnyh_jscss

[Reprinted] javascript and css for website front-end performance optimization-website performance optimization

Related Article

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.