22 tips for optimizing jquery performance

  • 2020-03-30 03:05:02
  • OfStack

First, keep in mind that jQuery is javascript. This means that we should adopt the same coding conventions, style guides, and best practices.

First of all, if you are a javascript novice, I suggest you to read the 24 javascript Best Practices for Beginners ", this is a high quality of javascript tutorial, contact the jQuery Best read before.

When you're ready to use jQuery, I highly recommend following these guidelines:

1. Cache variables

DOM traversal is expensive, so try to cache the elements that will be reused.


// bad 
h=$('#element').height();
$('#element').css('height',h-20);


// advice 
$element=$('#element');
h=$element.height();
$element.css('height',h-20);

2. Avoid global variables

Like javascript, jQuery is generally best used to make sure your variables are in function scope.


// bad 
$element=$('#element');
h=$element.height();
$element.css('height',h-20);


// advice 
var $element=$('#element');
var h=$element.height();
$element.css('height',h-20);

3. Use Hungarian nomenclature

Prefix the variable with $to identify the jQuery object.


// bad 
var first=$('#first');
var second=$('#second');
var value=$first.val();


//Suggestion - prefix jQuery objects with $prefix & NBSP;  
var $first=$('#first');
var $second=$('#second'),
var value=$first.val();

4. Use var chain (single var mode)

Combining multiple var statements into one statement, I recommend putting the unassigned variables later.


var
  $first=$('#first'),
  $second=$('#second'),
  value=$first.val(),
  k=3,
  cookiestring='SOMECOOKIESPLEASE',
  i,
  j,
  myArray={};

5. Please use 'on'

In the new jQuery, the shorter on("click") is used to replace functions like click(). In the previous version, on() was bind(). Since jQuery version 1.7, on() has been the preferred method for attaching event handlers. However, for consistency, you can simply use the on() method entirely.


// bad 
$first.click(function(){
    $first.css('border','1px solid red');
    $first.css('color','blue');
});
$first.hover(function(){
    $first.css('border','1px solid red');
})


//  advice 
$first.on('click',function(){
    $first.css('border','1px solid red');
    $first.css('color','blue');
})
$first.on('hover',function(){
    $first.css('border','1px solid red');
})

6. Concise javascript

In general, it is best to merge functions whenever possible.


// bad 
$first.click(function(){
    $first.css('border','1px solid red');
    $first.css('color','blue');
});


// advice 
$first.on('click',function(){
    $first.css({
        'border':'1px solid red',
        'color':'blue'
    });
});

7. Chain operation

JQuery implements the chain operation of methods very easily. So let's take advantage of that.


// bad 
$second.html(value);
$second.on('click',function(){
    alert('hello everybody');
});
$second.fadeIn('slow');
$second.animate({height:'120px'},500);


// advice 
$second.html(value);
$second.on('click',function(){
    alert('hello everybody');
}).fadeIn('slow').animate({height:'120px'},500);

8. Maintain code readability

Along with streamlining the code and using chaining, it can be difficult to read. Adding tightening and line breaks works well.


// bad 
$second.html(value);
$second.on('click',function(){
    alert('hello everybody');
}).fadeIn('slow').animate({height:'120px'},500);


// advice 
$second.html(value);
$second
    .on('click',function(){ alert('hello everybody');})
    .fadeIn('slow')
    .animate({height:'120px'},500);


9. Select short circuit evaluation

Short circuit evaluation is an expression that evaluates from left to right, using the ampersand (logical and) or || (logical or) operators.


// bad 
function initVar($myVar) {
    if(!$myVar) {
        $myVar=$('#selector');
    }
}


// advice 
function initVar($myVar) {
    $myVar=$myVar || $('#selector');
}
10.  Choose a shortcut 
 One way to streamline your code is to take advantage of coding shortcuts. 
[code]
// bad 
if(collection.length > 0){..}


// advice 
if(collection.length){..}

Separation of elements in heavy operations

If you're going to do a lot with DOM elements (setting multiple attributes or CSS styles in a row), it's recommended to separate the elements first and then add them.


// bad 
var
    $container=$("#container"),
    $containerLi=$("#container li"),
    $element=null;
$element=$containerLi.first();
//. Many complex operations


// advice 
var
    $container=$("#container"),
    $containerLi=$container.find("li"),
    $element=null;
$element=$containerLi.first().detach();
//. Many complex operations
$container.append($element);

Memorize skills

You may be inexperienced with the methods in jQuery, be sure to check the documentation, and there may be a better or faster way to use it.


// bad 
$('#id').data(key,value);


//Suggestions (efficient)
$.data('#id',key,value);

13. Use a child to query the parent element of the cache

As mentioned earlier, DOM traversal is an expensive operation. The typical approach is to cache the parent elements and reuse them when selecting the child elements.


// bad 
var
    $container=$('#container'),
    $containerLi=$('#container li'),
    $containerLiSpan=$('#container li span');


//Suggestions (efficient)
var
    $container=$('#container '),
    $containerLi=$container.find('li'),
    $containerLiSpan= $containerLi.find('span');


14. Avoid generic selectors

Placing generic selectors in descendant selectors is a poor performance.


// bad 
$('.container > *');


// advice 
$('.container').children();

15. Avoid implicit generic selectors

Generic selectors are sometimes implicit and not easy to find.


// bad 
$('.someclass :radio');


// advice 
$('.someclass input:radio');

16. Optimize the selector

For example, the id selector should be unique, so there is no need to add additional selectors.


// bad 
$('div#myid');
$('div#footer a.myLink');


//  advice 
$('#myid');
$('#footer .myLink');

Avoid multiple ID selectors

Here, it is emphasized that ID selectors should be unique, and there is no need to add additional selectors, not to mention multiple descendant ID selectors.


// bad 
$('#outer #inner');


// advice 
$('#inner');

Stick to the latest version

Get rid of deprecations

It is important to keep an eye on the discard methods for each new release and try to avoid them.


//Awful - live has been abandoned & NBSP;
$('#stuff').live('click',function() {
  console.log('hooray');
});


//  advice 
$('#stuff').on('click',function() {
  console.log('hooray');
});
//Note: this may not be appropriate, because live can implement real-time binding, delegate may be more appropriate

20. Use the CDN

Google's CND ensures that the cache closest to the user is selected and responds quickly. (please search the address by yourself if you use Google CND, the address here is not available, recommend the CDN provided by jquery official website).

21. Combine jQuery and javascript native code when necessary

As mentioned above, jQuery is javascript, which means that what you can do with jQuery, you can also do with native code. Native code (or vanilla) is probably not as readable and maintainable as jQuery, and the code is longer. But it also means being more efficient (usually the closer to the underlying code, the less readable it is, the higher the performance, for example: assembly, which of course requires more powerful talent). Keep in mind that no framework is smaller, lighter, or more efficient than native code.

Given the performance differences between vanilla and jQuery, I strongly recommend taking the best of both worlds and using (if possible) native code equivalent to jQuery.

22. Final advice

Finally, my goal in documenting this article is to improve the performance of jQuery and some other good Suggestions. If you want to delve into this topic you will find a lot of fun. Remember, jQuery is not a must-have, just an option. Think about why you're using it. DOM manipulation? Ajax? Template? CSS animations? Selector engine? Perhaps a custom version of the javascript mini-framework or jQuery would be a better choice.


Related articles: