jquery Performance Tuning Guide

Source: Internet
Author: User
Tags event listener


Always inherit from ID selector

The fastest selector in jquery is the ID selector because it comes directly from the JavaScript getElementById () method.
For example, there is an HTML code:
Code

<div id= "Content" >
<form method= "POST" action= "#" >
<ul id= "Traffic_light" >
<li><input type= "Radio" class= "on" name= "Light" value= "red"/> Red </li>
<li><input type= "Radio" class= "Off" name= "light" value= "yellow"/> Yellow </li>
<li><input type= "Radio" class= "Off" name= "Light" value= "green"/> Green </li>
</ul>
<input class= "button" id= "Traffic_button" type= "Submit" value= "Go"/>
</form>
</div>

If you use the selector below, efficiency is inefficient.

var Traffic_button = $ ("#content. Button");

Since the button already has an ID, we can use the ID selector directly. As shown below:

var Traffic_button = $ ("#traffic_button");

Of course, this is only for a single element. If you need to select multiple elements, this will inevitably involve DOM traversal and looping,
To improve performance, it is recommended that you inherit from the nearest ID.
As shown below:

var traffic_lights = $ ("#traffic_light input");





Use tag in front of Class (label signature)
The second fastest selector in jquery is the tag selector (for example, $ ("Head")).
When tired with the ID selector, it comes from the native getElementsByTagName () method.

Go ahead and look at the HTML code just now:
text box

<div id= "Content" >
<form method= "POST" action= "#" >
<ul id= "Traffic_light" >
<li><input type= "Radio" class= "on" name= "Light" value= "red"/> Red </li>
<li><input type= "Radio" class= "Off" name= "light" value= "yellow"/> Yellow </li>
<li><input type= "Radio" class= "Off" name= "Light" value= "green"/> Green </li>
</ul>
<input class= "button" id= "Traffic_button" type= "Submit" value= "Go"/>
</form>
</div>


For example, you need to select the Red and green Radio box,
Then you can use a tag name to limit (modify) the class as follows:

var active_light = $ ("Input.on");

Of course you can also combine the nearest ID, as shown below:

var active_light = $ ("#traffic_light Input.on");


When using tag to decorate class, we need to pay attention to the following points:
(1) Do not use tag to decorate the ID, as follows:

var content = $ ("div#content");


As a result, the selector iterates through all DIV elements and then matches #content.
(as if jquery had changed the selector core from 1.3.1, there was no problem.) Temporarily unable to verify. )

(2) Do not use the ID to decorate the ID with the superfluous, as follows:

var traffic_light = $ ("#content #traffic_light");


Note: If you use the attribute selector, use tag as much as possible, as follows:

$ (' p[row= ' c3221 "]). HTML (); instead of this: $ (' [row= ' c3221 '] '). html ();





Cache a jquery Object
Caching jquery objects is about telling us to get into the habit of caching jquery objects into variables.
Here's a new piece of jquery handwritten code:

Original code

$ ("#traffic_light Input.on"). Bind ("click", Function () {});
$ ("#traffic_light Input.on"). CSS ("Border", "1px dashed yellow");
$ ("#traffic_light Input.on"). CSS ("Background-color", "orange");
$ ("#traffic_light Input.on"). FadeIn ("slow");


But remember not to do so.
We should first cache the object into a variable and then manipulate it as follows:
New Code

var $active _light = $ ("#traffic_light Input.on");
$active _light.bind ("click", Function () {});
$active _light.css ("Border", "1px dashed yellow");
$active _light.css ("Background-color", "orange");
$active _light.fadein ("slow");


Remember, never let the same selector appear multiple times in your code.
The above code can be improved using jquery's chained operation
New Code 2

var $active _light = $ ("#traffic_light Input.on");
$active _light.bind ("click", Function () {})
. CSS ("Border", "1px dashed yellow")
. CSS ("Background-color", "orange")
. FadeIn ("slow");


If you intend to use jquery objects in other functions, you must cache them in the global environment.
As shown in the following code:
Code

Defining an object at the global scope (for example: Window object)
window. $my = {
Head: $ ("head"),
Traffic_light: $ ("#traffic_light"),
Traffic_button: $ ("#traffic_button")
};
function do_something () {
Now you can reference the stored results and manipulate them
var script = document.createelement ("script");
$my. Head.append (script);
As you work inside the function, you can continue to save the query to the global object.
$my. Cool_results = $ ("#some_ul Li");
$my. Other_results = $ ("#some_table TD");
Use the global function as a normal jquery object.
$my. Other_results.css ("Border-color", "Red");
$my. Traffic_light.css ("Border-color", "green");
}
You can also use it in other functions





Restrict direct DOM operations
The basic idea here is to build what you really want in memory and then update the DOM.
This is not a jquery best practice, but it must be done in a valid JavaScript operation. The direct DOM operation is slow.
For example, if you want to create a list of elements dynamically, do not do so, as follows:
Original code

var top_100_list = [],//Suppose this is a 100 unique string
$mylist = $ ("#mylist"); JQuery selection to <ul> elements
For (var i=0, l=top_100_list.length; i<l; i++) {
$mylist. Append ("<li>" + top_100_list[i] + "</li>"); Performed 100 times Append
}


We should create the entire set of element strings before inserting them into the DOM, as follows:
New Code

var top_100_list = [], $mylist = $ ("#mylist"), Top_100_li = ""; This variable will be used to store our list elements.
For (var i=0, l=top_100_list.length; i<l; i++) {
Top_100_li + = "<li>" + top_100_list[i] + "</li>"; 100 operations are variables in operation, regardless of DOM, speed is very much faster
}
$mylist. HTML (TOP_100_LI);


The Legendary Junk code

for (i = 0; i <; i++) {
var $myList = $ (' #myList ');
$myList. Append (' This is List item ' + i);
}





Bubble
Except in special cases, each JS event (for example: click, mouseover, etc.) Will bubble to the parent node.
This is useful when we need to invoke the same function for multiple elements.
Instead of this inefficient multi-element event listener, you only have to bind to their parent node once.
For example, we want to bind to a form that has many input boxes: Add a class to it when the input box is selected
The traditional approach is to select input directly, then bind focus, and so on, as follows:
Original code

$ ("#entryform input"). Bind ("Focus", function () {
$ (this). AddClass ("selected");
}). bind ("Blur", function () {
$ (this). Removeclass ("selected");
});


Of course the above code can help us do the task, but if you want to find a more efficient way, please use the following code:
New Code

$ ("#entryform"). Bind ("Focus", function (e) {
var $cell = $ (e.target); E.target snapping to the triggering target element
$cell. AddClass ("selected");
}). bind ("Blur", function (e) {
var $cell = $ (e.target);
$cell. Removeclass ("selected");
});


The target element is manipulated by listening for the event that gets focus and loses focus at the parent level.
In the code above, the parent element plays the role of a dispatcher, which can bind events based on the target element.
If you find that you have a lot of elements that are bound to the same event listener, now you know what's wrong.

Similarly, in table operations, we can also use this approach to improve the code:
The normal way:

$ (' #myTable TD '). Click (function () {
$ (this). CSS (' background ', ' red ');
});

How to Improve:

$ (' #myTable '). Click (function (e) {
var $clicked = $ (e.target);
$clicked. CSS (' background ', ' red ');
});

Assuming there are 100 TD, you are bound to 100 events when using the normal way.
In the improved mode, you only have 1 events bound for one element,
As for the high efficiency of the 100 events or the high efficiency of the 1 events, I believe you can distinguish them by yourself.




Deferred to $ (window). Load
jquery is a tempting thing for developers to hook anything up to $ (document).
Although $ (document). Rady is really useful, it can be executed when the page is rendered and other elements have not been downloaded.
If you find that your page has been loaded in the state, it is likely that $ (document). The Ready function is causing the.

You can reduce the CPU usage on page load by binding the jquery function to the $ (window) Load event method.
It will be executed after all the HTML (including <iframe>) has been downloaded.

$ (window). Load (function () {
The jquery function that was initialized after the page was fully loaded.
});




compressing JavaScript
Compress and minimize your JavaScript files.

Online compression Address:
http://dean.edwards.name/packer/
http://yui.2clics.net/
http://javascriptcompressor.com/
Before compressing, please ensure that your code is normative, otherwise it may fail, leading to JS error.




Try to use ID instead of class
Original code

Create a list
var $myList = $ (' #myList ');
var mylistitems = ' <ul> ';
for (i = 0; i <; i++) {
Mylistitems + = ' <li class= ' listItem ' + i + ' ">this is a list item</li> '; The class is used here.
}
Mylistitems + = ' </ul> ';
$myList. HTML (mylistitems);
Select each of the LI
for (i = 0; i <; i++) {
var SelectedItem = $ ('. ListItem ' + i);
}


At the end of the code, it took a total of 5066 milliseconds, more than 5 seconds, to select each li.
Then we make a comparison with the ID instead of class:


New Code

Create a list
var $myList = $ (' #myList ');
var mylistitems = ' <ul> ';
for (i = 0; i <; i++) {
Mylistitems + = ' <li id= ' listItem ' + i + ' ">this is a list item</li> '; The ID is used here.
}
Mylistitems + = ' </ul> ';
$myList. HTML (mylistitems);
Select each of the LI
for (i = 0; i <; i++) {
var SelectedItem = $ (' #listItem ' + i);
}

In the previous code, selecting each Li took a total of 61 milliseconds, nearly 100 times times faster than class.





Give the selector a context
There is one such selector in the jquery selector, which can specify the context.

JQuery (expression, context);

With it, you can reduce the range of selectors in the DOM to save time and improve efficiency.
Normal way:

$ ('. Mydiv ')

How to Improve:

$ ('. Mydiv ', $ ("#listItem"))




Use the. Live () method sparingly (should say try not to use)

This is an addition to the jQuery1.3.1 version, and the function of this method is to dynamically bind events to the new DOM elements.
But for efficiency, this method is more resource-intensive. So please try not to use it.

Original code

<script type= "Text/javascript" >
$ (function () {
$ ("P"). Click (function () {
Alert (This). text ());
});
$ ("button"). Click (function () {
$ ("<p>this is second p</p>"). AppendTo ("body");
});
})
</script>
<body>
<p>this is first p</p> <button>add</button>
</body>


After running, you will find the new P element and no use being bound by the Click event.
You can change to. Live ("click") to resolve this issue, the code is as follows:


New Code

$ (function () {
$ ("P"). Live ("Click", Function () {///change to Live mode
Alert (This). text ());
});
$ ("button"). Click (function () {
$ ("<p>this is second p</p>"). AppendTo ("body");
});
});

But it is not recommended to do so, the old way to solve the problem, the code is as follows:

Old method

$ (function () {
$ ("P"). Click (function () {
Alert (This). text ());
});
$ ("button"). Click (function () {
$ ("<p>this is second p</p>"). Click (function () {//to rebind the new element once
Alert (This). text ());
}). AppendTo ("body");
});
})


jquery Performance Tuning Guide

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.