Best Practices for Web Program optimization: JavaScript and CSS

Source: Internet
Author: User
Tags blank page website performance

Yahoo! 's exceptional Performance Team delivers best practices for improving Web performance. They carried out a series of experiments, developed tools, wrote a large number of articles and blogs, and participated in discussions at various conferences. At the heart of best practices is the goal of improving website performance.

The Excetional Performance Team summed up a series of ways to improve website speed. Can be divided into 7 major categories 34. Includes seven parts, including content, servers, cookies, CSS, JavaScript, pictures, mobile apps, and more.

This article is for the CSS and JavaScript sections:

In addition, JavaScript and CSS are often used in our pages, and the optimization of them will also improve the performance of the site important aspects:

Css:

1. Place the style sheet on top

2. Avoid using CSS expressions (expression)

3. Using external JavaScript and CSS

4. Cut JavaScript and CSS

5. Replace @import with <link>

6. Avoid using filters

Javascript

7. Place the script at the bottom of the page

8. Using external JavaScript and CSS

Cut JavaScript and CSS and reject duplicate scripts (refer to 3, 4)

9. Reduce DOM Access

10. Develop Intelligent event handlers

1. Place the style sheet on top

When we looked at Yahoo! 's performance, we found that placing the stylesheet inside the

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

2. Avoid using CSS expressions (expression)

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:

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 in a cross-browser design

This is useful when you are setting up for Internet Explorer separately. 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.

Many sites do not have the functionality to build these metrics. The best way to resolve these sites is to refer to JavaScript and CSS as external files. The exception to using built-in code is the homepage of the website, such as Yahoo! Home and my Yahoo! The home page has fewer (and perhaps only one) views in a session, and you can see that built-in JavaScript and CSS speed up response times for end users.

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.

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 reducing external script and stylesheet files,,<script> and <style> blocks can and should be reduced. 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 with <link>

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.

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

This can be delayed, then it can be moved to the bottom of the page. This will make your page load a little faster.

8. Eliminate duplicate scripts

Repeatedly referencing JavaScript files on the same page can affect the performance of the page. You might think that this situation

is rare. 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 refer to a script using <script/> tags in an HTML page is to:

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

9. 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 the nodes to the document tree after they are updated at the end of the line

• Avoid using JavaScript to modify page layouts

For more information on this, please see the article "High-performance Ajax should program" in Julien Lecomte in the Yui topic.

10. 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. You might want to replace onload with the Domcontentloaded event, but you can use the Onavailable method in the Yui event application before all browsers support it.

For more information on this, please see the article "High-performance Ajax should program" in Julien Lecomte in the Yui topic.

Best Practices for Web Program optimization: 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.