Ten quick improvements to JQuery performance make your JQuery run faster

Source: Internet
Author: User

This article provides ten steps to immediately improve the performance of your script. Don't worry. This is not an advanced technique. Everyone can use it! These skills include:
Use the latest version
Merge and minimize scripts
Replacing each with
Replace class selector with ID
Specify the front and back text for the selector
Create Cache
Avoid DOM operations
Avoid using concat () and use join () to process long strings
Returns false.
Using cheat sheet and reference documents
Use the latest version
JQuery has been in constant development and improvement processes. John and his team are constantly researching new ways to improve program performance.
A few months ago, he also released Sizzle, a JS selector library that is said to be able to improve program performance by three times in Firefox.
If you don't want to keep an eye on whether a new version is available and then spend time downloading and uploading it, Google will help you again. Their servers store a large number of Ajax libraries for you to choose from.
Copy codeThe Code is as follows:
<! -- Call an API using a simple script tag -->
<Script type = "text/javascript" src = "http://www.google.com/jsapi"> </script>
<Script type = "text/javascript">
/* Load jQuery v1.3.2 */
Google. load ("jquery", "1.3.2", {uncompressed: false });
/* Pop up the message after loading */
Function onLoad (){
Alert ("jQuery + Google API! ");
}
Google. setOnLoadCallback (onLoad );
</Script>

Another simpler and faster method is to directly use the script link. If you want to use a specific version of jQuery, you can use the above method. If you want to use the latest version directly, the following code is enough:
Copy codeThe Code is as follows:
<Script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"> </script>

You can also load a specific version as follows:
Copy codeThe Code is as follows:
<Script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"> </script>

Merge and minimize scripts
Most browsers cannot process multiple script files at the same time, so the loading time is also extended.
Considering that these scripts are loaded on every page of your website, you should consider placing them in a single file, and then using the compression tool (such as Dean Edwards) to minimize them. Smaller files will undoubtedly increase the loading speed.
JavaScript and CSS compression are designed to reduce the number of bytes transmitted while maintaining the execution performance of the script (you can reduce the size of the original file or use gzip. Most product-level network servers use gzip as part of the HTTP protocol ). Derived from YUI compressor, a compression script tool officially recommended by jQuery.
Replacing each with
Native functions are always faster than helper components.
If you need to traverse an object (such as a JSON Object received remotely), You 'd better rewrite your (JSON) object into an array, so it is easier to process the array cyclically.
With Firebug, we can determine the execution time of each function.
Copy codeThe Code is as follows:
Var array = new Array ();
For (var I = 0; I <10000; I ++ ){
Array [I] = 0;
}
Console. time ('native '); // native for Function
Var l = array. length;
For (var I = 0; I <10000; I ++ ){
}


The above results show that the native code only needs 2 ms, and the use of jQuery's each method takes 26 Ms. In addition, this is only the result of testing a function that basically has nothing to do on the local machine. In more complex cases, such as setting css attributes or DOM operations, the time difference must be greater.
Replace class selector with ID
Using ID to select an object is much better, because jQuery uses the native function getElementByID () of the browser to get the object, and the query speed is very fast.
Therefore, it is worthwhile to use a more complex selector than to use those convenient css selection techniques (jQuery also provides us with a complex selector ). You can also manually write your selector (which is simpler than you think), or specify an ID container for the element you want to select.
Copy codeThe Code is as follows:
// Create a list in the following example and fill in the entry content
// Each entry is selected once.
// Select using class first
Console. time ('class ');
Var list = $ ('# list ');
Var items ='
';
For (I = 0; I <1000; I ++ ){
Items + ='
Item
';
}
Items + ='
';
List.html (items );
For (I = 0; I <1000; I ++ ){
Var s = $ ('. item' + I );
}
Console. timeEnd ('class ');
// Use the ID to select
Console. time ('id ');
Var list = $ ('# list ');
Var items ='
';
For (I = 0; I <1000; I ++ ){
Items + ='
Item
';
}
Items + ='
';
List.html (items );
For (I = 0; I <1000; I ++ ){
Var s = $ ('# item' + I );
}
Console. timeEnd ('id ');

The above example demonstrates the significant performance differences between different selection methods. Please see, using class for selection, the time is infinitely increased, or even more than five seconds.
Specify the front and back text for the selector
The reference document of jQuery says: the front and back texts passed to the original DOM node of jQuery () (if nothing is passed, the front and back texts are the whole document ). The purpose is to achieve more accurate query together with the selector.
Therefore, if you must use the class to specify the target, at least specify the context for the selector to avoid jQuery's effort to traverse the entire DOM document:
Write it like this:
Copy codeThe Code is as follows:
Certificate ('.class'0000.css ('color' #123456 ');

It is better to add the front and back texts to the selector (expression: Target selector; context: front and back texts ):
Copy codeThe Code is as follows:
$ (Expression, context)

That is to say:
Copy codeThe Code is as follows:
$ ('. Class', '{class-container'}.css ('color',' #123456 ');

This is much faster because it does not need to traverse the entire DOM. You only need to find # class-container.
Create Cache
Do not make the mistake of constantly selecting the same thing. You should cache the elements you want to process as a variable.
Do not repeatedly select the same element in a loop! This operation affects the speed!
Copy codeThe Code is as follows:
Items ('items item'detail .css ('color', '#123456 ');
Items ('items item'items .html ('hello ');
Certificate ('background item'0000.css ('background-color', '# ffff ');
// Write better
('Items item'0000.css ('color', '0000123456'0000.html('hello'0000.css ('background-color', '# ffff ');
// Even like this
Var item = $ ('# item ');
Item.css ('color', '#123456 ');
Item.html ('hello ');
Item.css ('background-color', '# ffff ');
// Encounter a loop, which is very bad
Console. time ('no cache ');
For (var I = 0; I <1000; I ++ ){
$ ('# List'). append (I );
}
Console. timeEnd ('no cache ');
// This is much better
Console. time ('cache ');
Var item = $ ('# list ');
For (var I = 0; I <1000; I ++ ){
Item. append (I );
}
Console. timeEnd ('cache ');

Avoid DOM operations
The fewer DOM operations, the better, because the insert actions such as prepend (), append (), and after () are time-consuming. In the preceding example, html () is faster:
Copy codeThe Code is as follows:
Var list = '';
For (var I = 0; I <1000; I ++ ){
List + ='
'+ I +'
';
}
('{List'{.html (list );

Avoid using concat () and use join () to process long strings
It may sound strange, but doing so can really increase the speed, especially when the connection is particularly long. First, create an array and put it into the things you want to concatenate. The join () method is much faster than the concat () function of the string.
Copy codeThe Code is as follows:
Var array = [];
For (var I = 0; I <= 10000; I ++ ){
Array [I] ='
'+ I + '';
}
('{List'{.html (array. join (''));

"+ = Operator faster-faster than placing string fragments in an array and then joining them". "arrays used as string buffer are more efficient than strings in most browsers. prototype. concat. the apply method is more efficient, except Firefox 2.0.0.14 in Windows." -Tom Trenka
Returns false.
You may have noticed that if the function does not return false after execution, you will be redirected to the top of the page. If the page is long, this response is annoying.
Therefore, unlike this:
Copy codeThe Code is as follows:
$ ('# Item'). click (function (){
// Stuff here
});

It is better to add one more sentence:
Copy codeThe Code is as follows:
$ ('# Item'). click (function (){
// Stuff here
Return false;
});

Additional tips-cheat sheet and reference documents

This suggestion does not directly increase the execution speed of functions. However, if you are willing to spend time on this and study these tips and reference documents, you will save a lot of time in the future.
Please take a copy at your hand for quick reference.

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.