Tips and Tricks to improve JQuery efficiency
* Always use the latest version of jQuery core where possible.
* Use faster selector
- id selector, tag selector > class selector > pseudoclass selector, attribute selector
* Faster way to get child ele from a parent ele.
- $parent.find('.child')
* Don't use jQuery unless it's absolutely necessary
- javascript's original methods are faster.
* Do cache
- var parents = $('.parents'); // caching
{
// bad way
children = $('.parents').find('.child');
others = $('.parents').find('.others');
}
{
// better way, use cache
children = parents.find('.child');
others = parents.find('.others')
}
* Chaining
- e.g. var parents = $('.parents').doSomething().doSomethingElse();
- in this way, jQuery will cache the result of each step automatically,
so it's faster than non-chaining way.
* Use event delegation
- javascript allow events to bubble up the DOM tree to a parent element.
as "<table><tr></tr>...<tr></tr></table>", it's better to bind a single
event handler to <table> element than each <tr> element.
2 ways for delegation:
1) // .delegate() method
$("td").bind("click",function(){
$(this).toggleClass("click");
});
2) // .live() method
$("table").each(function(){
$("td",this).live("click", function(){
$(this).toggleClass("click");
});
});
Difference:
.delegate() fire when event bubble to the specific parent element.
.live() fire when event bubble to the root element.
so .delegate() is a little faster than .live()
* You'd better not to modify the DOM tree
- each DOM insertion is costly. so be careful to use append(),
insertBefore(), insertAfter()
if you want to insert several element items, you can put them together
and use a single append() method
- when you're doing heavy interaction with a node, you should use .detach() method first.
- if you're to attach data to a node, please use $.data(elem,key,value)
//bad
var ele = $('#elem');
ele.data(key, value);
//good, 10 times faster than above one
var ele = $('#elem');
$.data(ele, key, value);
* Understand loops
- unless absolutely necessary, avoid loops.
- javascript's for, while statement is faster than jQuery.each() method
* Avoid constructing new jQuery object unless necessary
- // slower
var $text = $('#text');
var $ts = $text.text();
// faster
var $text = $('#text');
var $ts = $.text($text);
// http://addyosmani.com/jqprovenperformance/