I found this article <jQuery Performance Rules> on twitter, I briefly translated it:
Always inherit from the ID selector
Use before class tag
Cache jquery objects
Master powerful chain operations
Use subqueries
Limit direct DOM operations
Bubble
Eliminate invalid queries
Delay to $(window).load
Compress js
Comprehensive mastery of the jquery library
1. Always inherit from the ID selector
The fastest selector in jquery is the ID selector. Because it directly The getElementById() method from Javascript.
Selecting buttons like this is inefficient:
var traffic_button = $('#content .button');
Select directly with ID Buttons are more efficient:
var traffic_button = $('# traffic_button');
Select multiple elements
Mentioning multi-element selection is actually talking about DOM traversal and looping, which are relatively slow things. In order to improve performance, it is best to So start inheriting from the nearest ID.
var traffic_lights = $ ('#traffic_light input');
2. Use tag before class
The second fastest selector is the tag selector ($('head')). Similarly, because It comes from the native getElementsByTagName() method.
Always limit (modify) classes with a tag name (and don’t forget the nearest ID):
var active_light = $('#traffic_light input.on');
Note: Class is the slowest selector in jquery. Under IE browser, it will traverse all DOM nodes regardless of where they are used.
Do not use tag name. Modify ID. The following example will traverse all div elements to find which node has the id 'content':
var content = $('div#content');
Modifying the ID with ID is superfluous:
var traffic_light = $('#content #traffic_light');
3. Cache jquery objects
To develop the habit of caching jquery objects into variables.
Never do this:
$('#traffic_light input .on).bind('click', function(){…});
$('#traffic_light input.on).css('border', '3px dashed yellow');
$(' #traffic_light input.on).css('background-color', 'orange');
$('#traffic_light input.on).fadeIn('slow');
Most It is best to cache the object into a variable first and then operate:
var $active_light = $('#traffic_light input.on');
$active_light.bind('click', function(){…});
$active_light.css('border', '3px dashed yellow');
$active_light.css('background-color', 'orange');
$active_light.fadeIn('slow');
To remember our local Variables are encapsulations of jquery, usually with a $ as a variable prefix. Remember, never let the same selector appear multiple times in your code.
Cache jquery results for later use
If you plan to use jquery result objects in other parts of the program, or your function will be executed multiple times, then cache them in a global variable.
Define a global container to store jquery results, we You can reference them in other functions:
// In global Scope defines an object (for example: window object)
window.$my =
{
// Initialize all queries that may be used more than once
head : $('head'),
traffic_light : $('#traffic_light'),
traffic_button : $('#traffic_button')
};
function do_something()
{
// Now you You can reference the stored results and manipulate them
var script = document.createElement('script');
$my.head.append(script);
// When you operate inside a function Yes, you can continue to store the query in 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');
}
4. Master powerful chain operations
The above example can also be written like this:
var $active_light = $('#traffic_light input.on');$active_light. bind('click', function(){…})
.css('border', '3px dashed yellow')
.css('background-color', 'orange')
.fadeIn ('slow');
This allows us to write less code and make our js more lightweight.
5. Use subqueries
jQuery allows We use additional selector operations on a wrapped object. Because we are already saving a parent object in a variable, this greatly improves operations on its child elements:
For example, we can use the subquery method to capture the lights that are on or off, and cache them for subsequent operations.
var $traffic_light = $('#traffic_light'),
$active_light = $traffic_light.find('input.on'),
$inactive_lights = $traffic_light.find('input.off');
Tip: You can declare multiple local variables at once using comma separated methods – saving bytes
6. Limit 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 is required for valid JavaScript operations. Direct DOM manipulation is slow.
For example, if you want to dynamically create a set of list elements, never do this:
var top_100_list = [...], // Assume here are 100 unique strings
$mylist = $('#mylist'); // jQuery selection to
element for (var i=0, l=top_100_list.length; i{
$mylist.append('- ' top_100_list[i] '< /li>');
}
We should create the entire set of element strings before inserting them into the dom:
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{
top_100_li = ' ' top_100_list[i] '';
}
$mylist.html(top_100_li);
We wrap multiple elements into a single before inserting The parent node will be faster:
var top_100_list = [. ..],
$mylist = $('#mylist'),
top_100_ul = '
';for (var i=0, l=top_100_list.length; i{
top_100_ul = '- ' top_100_list[i] '
';
}
top_100_ul = '
'; //Close the unordered list
$mylist.replaceWith(top_100_ul);
If you have done the above and are still worried about performance issues, then:
Try jquery's clone() method, it will create a copy of the node tree, which allows you to perform DOM operations in an "offline" manner, and then put it back into the node tree when you complete the operation.
Use DOM DocumentFragments. As the author of jQuery said, its performance is significantly better than direct dom operation.
7. Bubbles
Unless under special circumstances, every js event (such as: click, mouseover, etc.) will bubble up to the parent node. This is useful when we need to call the same function on multiple elements.
Instead of this inefficient multi-element event listening method, you only need to bind once to their parent nodes and can calculate which node triggered the event.
For example, we want Binding behavior like this for a form with many input boxes: Adding a class to the input box when it is selected
Binding events like this is inefficient:
$('#entryform input).bind('focus', function(){
$(this).addClass('selected');
}).bind('blur', function(){
$(this).removeClass('selected');
});
We need to listen to the focus-getting and losing-focus events at the parent level:
$('#entryform').bind('focus', function(e){
var cell = $(e.target); // e.target grabs the node that triggered the event.
cell.addClass('selected');
}).bind('blur', function(e){
var cell = $(e.target);
cell.removeClass('selected');
});
The parent element plays the role of a dispatcher, which can bind events based on the target element. If you find that you have bound the same event listener to many elements, then you must have done something wrong.
8 .Eliminate invalid queries
Although jquery can handle the situation of no matching elements very elegantly, it still takes time to find. If you only have one global js for the entire site, then it is very likely that all jquery functions will be stuffed into $ (document)ready(function(){//All the code you are proud of}).
Only run the functions used in the page. The most effective method is to use inline initialization functions, so that your Templates can accurately control when and where js should be executed.
For example, in your "article" page template, you may quote the following code at the end of the body:
Your global js library may look like this:
var mylib =
{
article_page :
{
init : function( )
{
// Article specific jQuery function.
}
},
traffic_light :
{
init : function()
{
/ / Traffic light’s unique jQuery function.
}
}
}
9. Defer to $(window).load
jquery for developers There is a very tempting thing, you can hang anything under $(document).ready to pretend to be an event. In most cases you will find this situation.
Although $(document).rady It is indeed very useful. It can be executed before other elements are downloaded when the page is rendered. If you find that your page is always loading, it is most likely caused by the $(document).ready function.
You can reduce the CPU usage when loading the page by binding the jquery function to the $(window).load event. It will be executed after all HTML (including