Home > Web Front-end > JS Tutorial > Summary of jQuery code performance optimization methods

Summary of jQuery code performance optimization methods

php中世界最好的语言
Release: 2018-04-23 15:30:17
Original
1477 people have browsed it

This time I will bring you jQuery codePerformance optimizationA summary of the method, what are the precautions for jQuery code performance optimization, the following is a practical case, let's take a look.

1. Always use #id to find element.

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

<p 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>
</p>
Copy after login
Copy after login
Copy after login

A way to select button with poor performance:

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

Instead, select the button directly:

var traffic_button = $('#traffic_button');
Copy after login

Select multiple elements

When we discuss selecting multiple elements, what we really need to know is that DOM traversal and looping are the cause of poor performance. To minimize performance loss, always use the nearest parent ID to find.

var traffic_lights = $('#traffic_light input');
Copy after login

2. Use Tags in front of Classes

The second fastest selector in jQuery is the Tag selector ($('head')). And this Because it maps directly to JavaScript's getElementsByTagName() method.

<p 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>
</p>
Copy after login
Copy after login
Copy after login

Always add a tag name in front of a Class (remember to pass it from an ID)

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

Note: The Class selector is the slowest choice in jQuery browser; in IE it loops through the entire DOM. Try to avoid using it if possible. Do not add Tags in front of the ID. For example, it will be very slow because it loops through all

elements to find the

whose ID is content.

var content = $('p#content');
Copy after login

Along the same lines, passing down from multiple IDs is redundant.

var traffic_light = $('#content #traffic_light');
Copy after login

3. Caching jQuery objects

Get into the habit of saving jQuery objects to a variable (like 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');
Copy after login

Instead, save the jQuery variable to a local variable before continuing your work.

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');
Copy after login

Tip: Use the $ prefix to indicate that our local variable is a jQuery package set. Remember, don't repeat jQuery selection operations more than once in your application. Bonus tip: Lazy storage of jQuery object results.

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

// Define an object in the global scope (i.e. the window object)
window.$my ={
 // Initialize all the queries you want to use more than once
 head : $('head'),
 traffic_light : $('#traffic_light'),
 traffic_button : $('#traffic_button')};
function do_something(){
 // Now you can reference the stored results and manipulate them
 var script = document.createElement('script');
 $my.head.append(script);
 // When working inside functions, continue to save jQuery results
 // to your global container.
 $my.cool_results = $('#some_ul li');
 $my.other_results = $('#some_table td');
 // Use the global functions as you would a normal jQuery result
 $my.other_results.css('border-color', 'red');
 $my.traffic_light.css('border-color', 'green');
}
Copy after login

4. Better utilization of the chain

The previous 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');
Copy after login

This allows us to write less code , making JavaScript more lightweight.

5, Using subqueries

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

<p 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>
</p>
Copy after login
Copy after login
Copy after login

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

var $traffic_light = $('#traffic_light'), 
$active_light = $traffic_light.find('input.on'), 
$inactive_lights = $traffic_light.find('input.off');
Copy after login

Tip: You can define multiple local variables at once separated by commas, which can save some bytes.

6. Limit direct DOM operations

The basic approach to DOM operations is to create a DOM structure in memory and then update the DOM structure. This is not the best approach for jQuery, but it is efficient for JavaScript. Directly manipulating DOM structures has low performance. For example, if you need to dynamically create a list of elements, don't do this:

var top_100_list = [...], // assume this has 100 unique strings 
$mylist = $('#mylist'); // jQuery selects our <ul> element
for (var i=0, l=top_100_list.length; i<l; i++){ 
 $mylist.append('<li>' + top_100_list[i] + '</li>');
}
Copy after login

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

var top_100_list = [...], // assume this has 100 unique strings 
$mylist = $('#mylist'), // jQuery selects our <ul> element 
top_100_li = ""; // This will store our list items
for (var i=0, l=top_100_list.length; i<l; i++){
 top_100_li += '<li>' + top_100_list[i] + '</li>';
}
$mylist.html(top_100_li);
Copy after login

A faster way, we should always include many elements in a parent node before inserting into the DOM structure

var top_100_list = [...], // assume this has 100 unique strings 
$mylist = $('#mylist'), // jQuery selects our <ul> element 
top_100_ul = '<ul id="#mylist">'; // This will store our entire unordered list
for (var i=0, l=top_100_list.length; i<l; i++){
 top_100_ul += '<li>' + top_100_list[i] + '</li>';
}
top_100_ul += '</ul>'; // Close our unordered list
$mylist.replaceWith(top_100_ul);
Copy after login

If you followed the above, you are still right If you are a little confused about performance, you can refer to the following:

* Try the Clone() method provided by jQuery. The Clone() method creates a copy of the node number, and you can then perform operations on this copy.

* Use DOM DocumentFragments. As the creator of jQuery points out, it is more performant than manipulating the DOM directly. Create the structure you need first (like we did with a string above), and then use jQuery's insert or replace methods.

7、事件委托(又名:冒泡事件)

除非特别说明,每一个JavaScript事件(如click, mouseover 等)在DOM结构树上都会冒泡到它的父元素上。如果我们想让很多elements(nodes)调用同一个function这是非常有用的。取而代之的是 你可以只对它们的父级绑定一次,而且可以计算出是哪一个节点触发了事件,而不是绑定一个事件监听器到很多节点上这种效率低下的方式。例如,假如我们要开发 一个包含很多input的大型form,当input被选择的时候我们想绑定一个class name。像这样的帮定是效率低下的:

$('#myList li).bind('click', function(){
 $(this).addClass('clicked'); // do stuff
});
Copy after login

反而,我们应该在父级侦听click事件。

$('#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
 }
});
Copy after login

父节点担当着发报机的工作,可以在触发了事件的目标element上做一些工作。如果你发现自己把一个event listener帮定到很多个element上,那么你这种做法是不正确的。

8、消除查询浪费

虽然jQuery对没有找到任何匹配的elements处理的很好,但是它还是需要花费时间去查找的。如果你的站点有一个全局的JavaScript,你可能会把每个jQuery function都放在 $(document).ready(function(){ // all my glorious code })里。 不要这样做。只去放一些页面上适合用到的function。这样做最有效的方式是你的模板可以完全控制任何时候或者地方执行JavaScript以内联脚 本的方式初始化function。例如,在你的“article”页面模板里,你可能在body标签关闭之前包含以下代码

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template