10 Fast boost jquery performance to make your jquery run faster _jquery

Source: Internet
Author: User
Tags documentation script tag
This article provides 10 steps to instantly improve your scripting performance. Don't worry, it's not a very advanced technique. Everyone can use it! These techniques include:
Use the latest version
merging, minimizing scripts
replace each with a for
replace the class selector with an ID
specify contextual for selector
Create a cache
Avoiding DOM Operations
Avoid using concat () to process long strings with join ()
return False Value
using small copy and reference documentation
Use the latest version
jquery has been in the process of continuous development and improvement. John and his team are constantly studying new ways to improve program performance.
A little digression, he also released a few months ago, a sizzle is said to be able to improve the program performance in Firefox 3 times times the JS selector library.
If you don't want to keep an eye out for new versions and then take the time to download and upload them, Google can help you again. They have a large number of Ajax libraries stored on their servers for you to choose from.
Copy Code code as follows:

<!--Invoke API--> with 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 message after completion of load/*
function OnLoad () {
Alert ("JQuery + Google api!");
}
Google.setonloadcallback (OnLoad);
</script>

Another simpler and faster way is to use script links directly. If you want to use a specific version of jquery, you can use the above method, and if you want to use the latest version directly, the following code is enough:
Copy Code code as follows:

<script type= "Text/javascript" src= "Http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js" ></script >

A specific version can also be loaded like this:
Copy Code code as follows:

<script type= "Text/javascript" src= "Http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" ></ Script>

Merging, minimizing scripts
Most browsers cannot handle multiple script files at the same time, so they are all queued-loading times are correspondingly prolonged.
Considering that every page of your site will load these scripts, you should consider putting them in a single file and then minimizing them using the compression tools (such as Dean Edwards). Smaller files will undoubtedly bring faster loading speeds.
The purpose of JavaScript and CSS compression is to reduce the number of bytes of data passing (either by reducing the original file or by taking advantage of Gzip) while maintaining the execution performance of the script. Most product-level Web servers use gzip as part of the HTTP protocol. From YUI compressor, a jquery official recommended compression script tool.
Replace each with a for
A native function is always faster than a secondary component.
If you encounter situations where you need to traverse an object (such as a JSON object that you receive remotely), you'd better rewrite your (JSON) object as an array, and the array will be easier to recycle.
Using Firebug, we can measure the execution time of each function.
Copy Code code 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 results above show that the native code is done in just 2 milliseconds, and each method using jquery takes 26 milliseconds. And that's just the result of a function I tested on my computer that basically didn't do anything, and when it comes to more complicated situations, such as setting CSS properties or DOM operations, the time difference is definitely greater.
Replace the class selector with an ID
Selecting objects with IDs is much better because jquery uses the browser's native function getElementById () to get the object and the query is fast.
Therefore, it is worthwhile to use a more complex selector than using those handy CSS selection techniques (jquery also provides us with complex selectors). You can also manually write your own selector (which is actually simpler than you think), or specify an ID container for the element you want to select.
Copy Code code as follows:

The following example creates a list and populates the contents of the entry
Each item is then selected once
First Use class selection
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 ');
Then 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 is a good illustration of the significant performance differences between the different options. Take a look at the picture below, use class to make a choice, time infinitely increased, even more than five seconds.
Specify contextual for Selector
The jquery reference document says, "Pass to jquery () The original DOM node's contextual (if nothing is passed, then contextual to the entire document)." The goal is to implement a more accurate query, along with selectors.
So, if you have to use class to specify the target, at least specify the context for the selector so that jquery does not have the energy to traverse the entire DOM document:
Instead of writing this:
Copy Code code as follows:

$ ('. class '). CSS (' color ' #123456 ');

It is better to add contextual to the selector (expression: target selector; context: Contextual):
Copy Code code as follows:

$ (expression, context)

Other words:
Copy Code code as follows:

$ ('. Class ', ' #class-container '). CSS (' color ', ' #123456 ');

This is much faster because it does not have to traverse the entire DOM. Just find #class-container.
Create a cache
Don't make mistakes that keep picking the same thing over and over again. You should cache the elements you are dealing with as a variable.
Not to repeat the same element in one cycle! This affects speed very much!
Copy Code code as follows:

$ (' #item '). CSS (' color ', ' #123456 ');
$ (' #item '). html (' hello ');
$ (' #item '). CSS (' Background-color ', ' #ffffff ');
It's better to write.
$ (' #item '). CSS (' color ', ' #123456 '). html (' Hello '). css (' Background-color ', ' #ffffff ');
Even so
var item = $ (' #item ');
Item.css (' Color ', ' #123456 ');
item.html (' Hello ');
Item.css (' Background-color ', ' #ffffff ');
It's very bad to have a loop.
Console.time (' no cache ');
for (var i=0; i<1000; i++) {
$ (' #list '). append (i);
}
Console.timeend (' no cache ');
It's a lot better down here.
Console.time (' cache ');
var item = $ (' #list ');
for (var i=0; i<1000; i++) {
Item.append (i);
}
Console.timeend (' cache ');

Avoiding DOM Operations
Dom operations should be as small as possible, as prepend (), append (), after () inserts are time-consuming. The above example will be faster if you use HTML ():
Copy Code code as follows:

var list = ';
for (var i=0; i<1000; i++) {
List + = '
' +i+ '
';
}
(' #list '). HTML (list);

Avoid using concat () to process long strings with join ()
It may sound strange, but doing so can really improve speed, especially if you are connected to a very long string. First set up an array and put in the things you want to concatenate. The join () method is much faster than the concat () function of the string.
Copy Code code as follows:

var array = [];
for (var i=0; i< =10000; i++) {
Array[i] = '
' +i+ ';
}
$ (' #list '). HTML (Array.join ('));

"+ = operator faster--faster than putting a string fragment into an array and then join it" as a string buffer (string Buffer) Arrays are more efficient than the String.prototype.concat.apply method in most browsers, with the exception of Firefox 2.0.0.14 under Windows. "-tom Trenka
return False value
You may have noticed that if the function does not return false after execution, you will be jumped to the top of the page. If the page is longer, this response is annoying.
So, rather than this:
Copy Code code as follows:

$ (' #item '). Click (function () {
Stuff Here
});

Why not add one more sentence:
Copy Code code as follows:

$ (' #item '). Click (function () {
Stuff Here
return false;
});

Extra tips – Small copy and reference documentation

This recommendation does not directly improve the execution speed of functions, but if you take the time to study these small copies and reference documents, you will be able to save a lot of time in the future.
Please keep a small copy at your fingertips for quick reference.

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.