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

Summary of jQuery code performance optimization methods

Apr 23, 2018 pm 03:30 PM
jquery optimization method

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标签关闭之前包含以下代码

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

The difference between Go language methods and functions and analysis of application scenarios The difference between Go language methods and functions and analysis of application scenarios Apr 04, 2024 am 09:24 AM

The difference between Go language methods and functions lies in their association with structures: methods are associated with structures and are used to operate structure data or methods; functions are independent of types and are used to perform general operations.

C++ program optimization: time complexity reduction techniques C++ program optimization: time complexity reduction techniques Jun 01, 2024 am 11:19 AM

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) May 07, 2024 pm 05:55 PM

Mobile phone film has become one of the indispensable accessories with the popularity of smartphones. To extend its service life, choose a suitable mobile phone film to protect the mobile phone screen. To help readers choose the most suitable mobile phone film for themselves, this article will introduce several key points and techniques for purchasing mobile phone film. Understand the materials and types of mobile phone films: PET film, TPU, etc. Mobile phone films are made of a variety of materials, including tempered glass. PET film is relatively soft, tempered glass film has good scratch resistance, and TPU has good shock-proof performance. It can be decided based on personal preference and needs when choosing. Consider the degree of screen protection. Different types of mobile phone films have different degrees of screen protection. PET film mainly plays an anti-scratch role, while tempered glass film has better drop resistance. You can choose to have better

How to optimize the startup items of WIN7 system How to optimize the startup items of WIN7 system Mar 26, 2024 pm 06:20 PM

1. Press the key combination (win key + R) on the desktop to open the run window, then enter [regedit] and press Enter to confirm. 2. After opening the Registry Editor, we click to expand [HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionExplorer], and then see if there is a Serialize item in the directory. If not, we can right-click Explorer, create a new item, and name it Serialize. 3. Then click Serialize, then right-click the blank space in the right pane, create a new DWORD (32) bit value, and name it Star

See all articles