10 ways to optimize jQuery code performance

  • 2021-06-29 09:41:29
  • OfStack

1. Always use #id to find element.

The fastest selector in jQuery is the ID selector ($('#someid'). This is because it maps directly to the getElementById() method of JavaScript.
Select a single element


<div id="content">

 <form method="post" action="/">

  <h2>Traffic Light</h2>

  <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>

Choose one way button does not perform well:


var traffic_button = $('#content .button');

Instead, choose button directly:


var traffic_button = $('#traffic_button');

Select multiple elements

When we talk about selecting multiple elements, what we really need to know is that traversal and looping of DOM are the reasons for the poor performance.To minimize performance loss, always use the closest parent ID to find.


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

2. Use Tags before Classes

The second fastest selector in jQuery is the Tag selector ($('head'). This is because it maps directly to the getElementsByTagName () method of JavaScript.


<div id="content">

 <form method="post" action="/">

  <h2>Traffic Light</h2>

  <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>

Always precede an Class with an tag name (remember to pass from an ID)


var active_light = $('#traffic_light input.on');

Note: The Class selector is the slowest one in jQuery;In IE it loops through DOM.Avoid using it whenever possible.Do not precede ID with Tags.For example, it would loop through all the < div > Element to find ID for content < div > And causes it to be very slow.


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

In the same way, passing down from multiple IDs is redundant.


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

3. Caching jQuery objects

Get into the habit of saving the jQuery object to a variable, as in the example above.For example, don't 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');

Instead, save the jQuery variable to a local variable for the first time before proceeding with your operation.


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');

Tip: Using $dropout means our local variable is an jQuery package set.Keep in mind that there should be no more than one jQuery duplicate selection in your program.Additional Tip: Delay storing jQuery object results.

If you want to use the jQuery result object elsewhere in your program (result object (s)), or if your function is executed multiple times, cache it in a global object.By defining a global container to hold the jQuery result object, you can reference it in other functions.


var traffic_button = $('#content .button');
0

4. Better use of chains

The previous examples can also be written as follows:


var traffic_button = $('#content .button');
1

This allows us to write less code and make JavaScript lighter.

5. Use subqueries

jQuery allows us to attach additional selectors to a package set.Because we have saved the parent object in the local variable, this reduces the performance overhead on the selector in the future.


var traffic_button = $('#content .button');
2

For example, we can use subqueries to cache active and inactive lights for later operations.


var $traffic_light = $('#traffic_light'), 

$active_light = $traffic_light.find('input.on'), 

$inactive_lights = $traffic_light.find('input.off');

Tip: You can define multiple local variables once separated by commas, which saves a few bytes.

6. Restrict direct operation on DOM

The basic practice of the DOM operation is to create an DOM structure in memory and then update the DOM structure.This is not the best practice for jQuery, but it is efficient for JavaScript.Direct operation of the DOM architecture is inefficient.For example, if you need to dynamically create a column of elements, do not do so:


var traffic_button = $('#content .button');
4

Instead, we want to create a set of elements in a string before inserting the DOM structure.
Code


var traffic_button = $('#content .button');
5

Faster, we should always include many elements in a parent node before inserting the DOM structure


var traffic_button = $('#content .button');
6

If you follow the above or are confused about performance, you can refer to the following:

*Try 1 for the Clone() method provided by jQuery.The Clone () method creates a copy of the number of nodes in which you can then operate.

*Using DOM DocumentFragments. As the creator of jQuery points out is better than directly operating DOM. Create the structure you need (as we did with 1 string above), then use insert or replace methods of jQuery.

7. Event Delegation (aka: Bubble Event)

Unless otherwise specified, each JavaScript event (e.g. click, mouseover, etc.) bubbles onto its parent element in the DOM structure tree.This is useful if we want many elements (nodes) calls to the same function.Instead of binding an event listener to many nodes, you can bind to their parent only once and calculate which node triggered the event.For example, if we want to develop a large form with many inputs, we want to bind an class name when input is selected.Help like this must be inefficient:


var traffic_button = $('#content .button');
7

Instead, we should listen to the click event at the parent.


$('#myList).bind('click', function(e){

 var target = e.target, // e.target grabs the node that triggered the event.

  $target = $(target); // wraps the node in a jQuery object

 if (target.nodeName === 'LI') {

  $target.addClass('clicked');  // do stuff

 }

});

The parent node serves as the transmitter and can do some work on the target element that triggered the event.If you find yourself placing an event listener on many elements, you are not doing the right thing.

8. Eliminate query waste

Although jQuery handles elements well when no match is found, it still takes time to find it.If your site has a global JavaScript, you may place each jQuery function in $(document). ready (function(){//all my glorious code}.Don't do this.Put only a few function pages that are suitable for use.The most effective way to do this is if your template has full control over executing JavaScript at any time or anywhere to initialize function in an inline script.For example, in your "article" page template, you may include the following code before the body tag closes

< script type="text/javascript > mylib.article.init(); < /script > < /body & gt;If your page template contains a variety of modules that may or may not be on the page, or you need them to be initialized later for visualization, you should place initialization functions immediately after those modules.


var traffic_button = $('#content .button');
9

Your global JavaScript library should look like this:


var mylib ={

 article_page : {

  init : function()  {

   // Article page specific jQuery functions. 

  }

 }, 

 traffic_light : {

  init : function()  {

   // Traffic light specific jQuery functions. 

  }

 }

}

9. Compliance with $(windows). load

There is a temptation to put everything jQuery developer hook does into the false event of $(document). ready.After all, this can be seen in most cases.Although $(document). ready is useful, it occurs when the page is rendered, although other objects are still being downloaded.If you find that your page pauses during download, it may be caused by $(document). ready.You can reduce the usage of CPU when downloading below by assigning jQuery functions to the $(window). load event, which calls all objects after all HTML (including iframe content) have been downloaded.


$(window).load(function(){

 // jQuery functions to initialize after the page has loaded.

});

Redundant functions, such as dragging and dropping, helping with visualization and animation, pre-reading pictures, etc., are better.

10. Compress JS

Although not related to jQuery, here's also a mention.Making JavaScript functions and variables readable is a trend that is essential for developers but has nothing to do with the average user.No excuse, it's time to incorporate JS compression into our workflow.Comment your code and find a compression tool to compress it before putting it into production.Use YUICompressor to compress extra wasted bytes in your code.In our experience, it can safely compress JavaScript as small as possible without taking up more CPU.Tip: To maximize compression in YUICompressor, you should define variables like this (for example, var my_long_variable_name;)

The best way to learn and use jQuery effectively is to check the documents and manuals of jQuery.


Related articles: