"Go" web site front-end performance optimizations for JavaScript and CSS

Source: Internet
Author: User
Tags blank page

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:

<type= "Text/javascript"  src= "Menu_1.0.17.js"></  script>

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>     <Scripttype= "Text/javascript" >//Cycle 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 code 1, in the first 5 seconds on the page is a blank, 5 seconds after the page is all displayed. Code 2, the first 5 seconds of BLOGJAVA,CSDN and so on first display, 5 seconds after MSN display.

It can be seen that embedding JS will block the rendering of all content, while external JS will only block the subsequent display of content, 2 ways will block the subsequent download of resources.

Embedded JS causes CSS blocking loading problems

How does a CSS block load? CSS can be downloaded in parallel, under what circumstances will appear blocking loading (in the test observation, IE6 under the CSS is blocked loading, the following test under non-IE6):

Code 1 (for the effect, here is a selection of 1 foreign server CSS):

<HTMLxmlns= "http://www.w3.org/1999/xhtml" >         <Head>           <title>JS Test</title>           <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"   />             <Linktype= "Text/css"rel= "stylesheet"href= "Http://69.64.92.205/Css/Home3.css"   />         </Head>         <Body>             <imgsrc= "Http://www.haorooms.com/images/logo.gif"   /><BR/>              <imgsrc= "Http://www.haorooms.com/images/csdnindex_piclogo.gif"   />         </Body></HTML> 

Time Waterfall Chart:

Code 2 (add only 1 empty embedded JS):

<Head>     <title>JS Test</title>     <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"   />     <Linktype= "Text/css"rel= "stylesheet"href= "Http://69.64.92.205/Css/Home3.css"   />   <Scripttype= "Text/javascript" >function A () {}</Script></Head><Body>         <imgsrc= "Http://www.haorooms.com/images/logo.gif"   /><BR/>         <imgsrc= "Http://www.haorooms.com/images/csdnindex_piclogo.gif"   /></Body>

Time Waterfall Chart:

From the time waterfall diagram can be seen, code 2, CSS and pictures are not parallel download, but wait for the CSS to download after the download of the next 2 images, when the CSS followed by embedded JS, the CSS will appear blocking the download of resources behind the situation.

Some people may ask, why not talk about embedded JS blocking the resources behind, but that CSS blocked? Think we now use 1 empty function, parse this empty function 1ms is enough, and the next 2 images are waiting for the CSS download 1.3s after downloading. You can also try to put embedded JS in front of the CSS, there will be no blocking situation.

Root cause: Because the browser will maintain the HTML in the order of CSS and JS, the stylesheet must be loaded before the embedded JS execution, parsing finished. Embedded JS will block the subsequent loading of resources, so the above CSS blocking download situation.

Embedded JS should be placed in what position

1, at the bottom, although placed at the bottom will still block all rendering, but will not block the download of resources.

2, if embedded JS placed in the head, please put embedded JS in front of the CSS.

3. Using defer

4, do not call in the embedded JS long-running function, if you must use, you can use SetTimeout to invoke, about SetTimeout, I wrote in an article earlier, please see: http://www.haorooms.com/post/js_setTimeout

Transferred from: HTTP://WWW.HAOROOMS.COM/POST/WEB_XNYH_JSCSS

"Go" web site front-end performance optimizations for JavaScript and CSS

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.