First of all, remember in your mind that jQuery is javascript. This means we should adopt the same coding conventions, style guides and best practices.
First of all, if you are a javascript newbie, I suggest you read "24 JavaScript Best Practices for Beginners", which is a high-quality javascript tutorial. It is best to read it before you get to jQuery.
When you are ready to use jQuery, I highly recommend that you follow these guidelines:
1. Cache variables
DOM traversal is expensive, so try to cache the reused elements.
//Oops
h=$('#element').height();
$('#element').css('height',h-20);
//suggestion
$element=$('#element');
h=$();
$('height',h-20);
2. Avoid global variables
jQuery Like javascript, generally speaking, it is best to make sure your variables are within the scope of the function.
//Oops
$element=$('#element');
h=$();
$('height',h-20);
//suggestion
var $element=$('#element');
var h=$();
$('height',h-20);
3. Use Hungarian nomenclature
Adding a $ prefix before the variable makes it easier to identify jQuery objects.
//Oops
var first=$('#first');
var second=$('#second');
var value=$();
// Suggestions - prefix the jQuery object
var $first=$('#first');
var $second=$('#second'),
var value=$();
4. Use var chain (single var mode)
Merge multiple var statements into one statement, and I suggest putting unassigned variables behind.
var
$first=$('#first'),
$second=$('#second'),
value=$(),
k=3,
cookiestring='SOMECOOKIESPLEASE',
i,
j,
myArray={};
5. Please use 'on'
In the new version of jQuery, the shorter on("click") is used to replace functions like click(). In previous versions, on() was bind(). Since jQuery version 1.7, on() is the preferred method for attaching event handlers. However, for consistency, you can simply use the on() method all.
//Oops
$(function(){
$('border','1px solid red');
$('color','blue');
});
$(function(){
$('border','1px solid red');
})
// suggestion
$('click',function(){
$('border','1px solid red');
$('color','blue');
})
$('hover',function(){
$('border','1px solid red');
})
6. Simplify javascript
Generally speaking, it is best to merge functions as much as possible.
//Oops
$(function(){
$('border','1px solid red');
$('color','blue');
});
//suggestion
$('click',function(){
$({
'border':'1px solid red',
'color':'blue'
});
});
7. Chain operation
The chain operation of jQuery implementation method is very easy. Take advantage of this below.
//Oops
$(value);
$('click',function(){
alert('hello everybody');
});
$('slow');
$({height:'120px'},500);
//suggestion
$(value);
$('click',function(){
alert('hello everybody');
}).fadeIn('slow').animate({height:'120px'},500);
8. Maintain code readability
With the simplification of the code and the use of chains, the code may be difficult to read. Adding tightening and line breaking can have a good effect.
//Oops
$(value);
$('click',function(){
alert('hello everybody');
}).fadeIn('slow').animate({height:'120px'},500);
//suggestion
$(value);
$second
.on('click',function(){ alert('hello everybody');})
.fadeIn('slow')
.animate({height:'120px'},500);
9. Select Short Circuit Value
Short circuit evaluation is an expression that evaluates from left to right, using the && (logical and) or || (logical or) operators.
//Oops
function initVar($myVar) {
if(!$myVar) {
$myVar=$('#selector');
}
}
//suggestion
function initVar($myVar) {
$myVar=$myVar || $('#selector');
}
10. Select a shortcut
One way to streamline code is to take advantage of coding shortcuts.
[code]
//Oops
if( > 0){..}
//suggestion
if(){..}
11. Separating elements in heavy operations
If you plan to do a lot of operations on DOM elements (set multiple attributes or css styles in succession), it is recommended to separate the elements first and then add them.
//Oops
var
$container=$("#container"),
$containerLi=$("#container li"),
$element=null;
$element=$();
//... Many complex operations
//suggestion
var
$container=$("#container"),
$containerLi=$("li"),
$element=null;
$element=$().detach();
//... Many complex operations
$($element);
12. Memorize the skills
You may lack experience with using methods in jQuery, be sure to view the documentation, and there may be a better or faster way to use it.
//Oops
$('#id').data(key,value);
// Suggestions (efficient)
$.data('#id',key,value);
13. Use subquery to cache parent elements
As mentioned earlier, DOM traversal is an expensive operation. Typically, cache the parent elements and reuse them when selecting children.
//Oops
var
$container=$('#container'),
$containerLi=$('#container li'),
$containerLiSpan=$('#container li span');
// Suggestions (efficient)
var
$container=$('#container '),
$containerLi=$('li'),
$containerLiSpan= $('span');
14. Avoid universal selectors
Putting the universal selector into the descendant selector has a very bad performance.
//Oops
$('.container > *');
//suggestion
$('.container').children();
15. Avoid implicit universal selectors
Common selectors are sometimes implicit and not easy to find.
//Oops
$('.someclass :radio');
//suggestion
$('.someclass input:radio');
16. Optimization selector
For example, the id selector should be unique, so there is no need to add additional selectors.
//Oops
$('div#myid');
$('div#footer ');
// suggestion
$('#myid');
$('#footer .myLink');
17. Avoid multiple ID selectors
It is emphasized here that the ID selector should be unique, and no additional selector is required, and more than multiple descendant ID selectors are required.
//Oops
$('#outer #inner');
//suggestion
$('#inner');
18. Stick to the latest version
New versions are usually better: lighter and more efficient. Obviously, you need to consider the compatibility of the code you want to support. For example, ie 6/7/8 is not supported in version 2.0.
19. Abandon the abandonment method
It is very important to focus on the abandoned methods of each new version and try to avoid them.
//Oh no-live is abandoned
$('#stuff').live('click',function() {
('hooray');
});
// suggestion
$('#stuff').on('click',function() {
('hooray');
});
// Note: This may be inappropriate, it should be that live can achieve real-time binding, delegate may be more suitable
20. Utilize CDN
Google's CND ensures that the cache closest to the user is selected and responds quickly. (Please search for the address by yourself when using Google CND. The address here cannot be used. It is recommended to use the CDN provided by jquery official website).
21. Combine jQuery and javascript native code if necessary
As mentioned above, jQuery is javascript, which means that what you can do with jQuery can also be done with native code. Native code (or vanilla) may not be readable and maintainable as jQuery, and the code is longer. But it also means more efficient (usually closer to the underlying code, the worse the readability, the higher the performance, such as assembly, of course, it requires more powerful talents). Remember that no framework can be smaller, lighter and more efficient than native code (Note: the test link has expired, you can search for the test code online).
Given the performance differences between vanilla and jQuery, I highly recommend absorbing the essence of both, using (if possible) native code equivalent to jQuery.
22. Final advice
Finally, the purpose of my documenting this post is to improve the performance of jQuery and some other good suggestions. If you want to dig deeper into this topic you will find a lot of fun. Remember, jQuery is not indispensable, it is just an option. Think about why you should use it. DOM operation? ajax? stencil? css animation? Or the selector engine? Perhaps a javascript mini framework or a custom version of jQuery is a better choice.