How to load your JavaScript page more quickly with js Performance Optimization

Source: Internet
Author: User
JavaScript is now extremely important. Some websites use JavaScript to add charm; many today's Web applications rely on it; some of them are even completely written in JavaScript. In this article, I will point out some important rules to show you how to use your JavaScript, what tools are used, and what benefits you will get from it to ensure that the Code is as concise as possible

Do not rely on JavaScript. Do not write repetitive scripts. JavaScript should be regarded as a candy tool, but it only plays a beautifying role. Do not add a lot of JavaScript code to your website. Use it only when necessary. It can only be used to improve user experience.

Minimize DOM access

It is easy to access DOM elements using JavaScript, and the code is easier to read, but the speed is slow. The following describes several key points: restrict the use of JavaScript to modify the webpage layout and cache reference for access elements. Sometimes, when your website depends on a large number of DOM changes, you should consider limiting your tag. This is a good reason to switch to HTML5 and discard the original XHTML and HTML4. You can view the number of DOM elements by entering document. getElementsByTagName ('*'). length in the Firebug plug-in console.

Compressed code

The most effective way to provide compressed JavaScript pages is to first compress your code with a JavaScript compression tool, which can compress variables and parameter names, then the obtained code is provided, and gzip compression is used.

Yes, I didn't compress my main. js, but you have to check whether there are any uncompressed jQuery plug-ins. Don't forget to compress them. Below I will list several compression solutions.

◆ YUI compression tool (used by the jQuery Development Team), beginner's Guide

(Http://www.slideshare.net/nzakas/extreme-JavaScript-compression-with-yui-compressor), second guide (http://vilimpoc.org/research/js-speedup/) and official website (http://developer.yahoo.com/yui/compressor ).

Http://dean.edwards.name/packer/ (Dean Edwards Packer)

Http://crockford.com/JavaScript/jsmin (JSMin)

GZip compression: The idea behind GZip compression is to shorten the time for data transmission between the browser and the server. After the time is shortened, you get a file named Accept-Encoding: gzip and deflate. However, this compression method has some disadvantages. It occupies processor resources (for compression and decompression) on both the server side and the client side, as well as disk space.

Avoid eval (): Although sometimes eval () brings some efficiency in time, it is absolutely wrong to use it. Eval () causes your code to look dirty and escape the compression of most compression tools.

Tool for accelerating JavaScript loading: Lab. js

There are many excellent tools to speed up JavaScript loading. One tool worth mentioning is Lab. js.

With LAB. js (loading and blocking JavaScript), you can load JavaScript files in parallel to speed up the overall loading process. In addition, you can set an order for the script to be loaded to ensure the integrity of the dependency. In addition, developers claim that their website speed has increased by two times.

Use appropriate CDN

Many Web pages now use the content delivery network (CDN ). It can improve your cache mechanism because everyone can use it. It can also save some bandwidth for you. It is easy for you to use ping detection or Firebug to debug those servers, so that you can find out which aspects can speed up data. When selecting CDN, you need to take care of the location of those visitors on your website. Remember to use a public repository whenever possible.

Several CDN solutions for jQuery:

◆ Success.

◆ Http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js--microsoft CDN

• Http://code.jquery.com/jquery-1.4.2.min.js--Edgecast (mt ).

Load JavaScript at the end of the page

If you are concerned about users and users have not left your webpage due to slow Internet connection speeds, this is a good practice. Ease of use and users are at the top, while JavaScript is at the end. This may be painful, but you should be prepared. Some users disable JavaScript. Some JavaScript to be loaded can be placed in the header, provided that it is loaded asynchronously.

Asynchronously load the tracking code

This is very important. Most of us use Google Analytics for statistics. This is good. Now let's take a look at where you put your tracking code. Is it in the header? Or does it use document. write? Then, if you do not use the Google analysis tool to asynchronously track code, you can only blame yourself.

This is how Google's analysis tool asynchronously tracks code. We must admit that it uses DOM instead of document. write, which may be more suitable for you. It can detect some of the events before loading the webpage, which is very important. Now let's think about this situation. Your webpage has not even been loaded, and all users have closed the webpage. You have found a solution to missed page views.

var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXXX-XX']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/JavaScript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();

Not using Google analysis tools? This is not a problem. Most of today's analysis tool providers allow you to use Asynchronous tracing.


Ajax Optimization

Ajax requests have a significant impact on the performance of your website. Next I will introduce several key points about Ajax optimization.

Cache your ajax

Let's take a look at your code. Can your ajax be cached? Yes, it depends on data, but most of your ajax requests can be cached. In jQuery, your request is cached by default, excluding the script and jsonp data types.

Use GET for Ajax requests

For a POST request, two TCP packets are sent (the title is sent first, and then the data is sent ). A GET request only needs to send one packet (depending on the number of cookies ). Therefore, when your URL is less than 2 K in length and you want to request some data, you may wish to use GET.

Use ySlow

Speaking of performance, ySlow is simple and extremely effective. It can rate your website, show which aspects need to be corrected, and what aspects should be paid attention.

Another trick: Package Your JavaScript into a PNG file.

Imagine: add your JS and CSS to the end of the image, then crop it with CSS, and get all the information required by the application through an HTTP request.

I recently found this method. It basically packs your JavaScript/css data into PNG files. You can use the getImageData () of the canvas API (). In addition, it is very efficient. You can compress the data by about 35% without narrowing down the data. And lossless compression! I have to point out that for a relatively large script, when the image points to the canvas and reads pixels, you will feel that there is a "Period" of loading time.

For more articles about how to load your JavaScript page more quickly with js performance optimization, refer to the PHP Chinese website!

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.