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

Summary of jQuery code performance optimization methods

php中世界最好的语言
php中世界最好的语言Original
2018-04-23 15:30:171283browse

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

 

  

Traffic Light

  
       
  •  Red
  •    
  •  Yellow
  •    
  •  Green
  •   
    

A way to select button with poor performance:

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

Instead, select the button directly:

var traffic_button = $('#traffic_button');

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

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.

 

  

Traffic Light

  
       
  •  Red
  •    
  •  Yellow
  •    
  •  Green
  •   
    

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

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

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

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

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

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

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

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

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

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.

 

  

Traffic Light

  
       
  •  Red
  •    
  •  Yellow
  •    
  •  Green
  •   
    

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

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 
     element for (var i=0, l=top_100_list.length; i' + top_100_list[i] + ''); }

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 
     element  top_100_li = ""; // This will store our list items for (var i=0, l=top_100_list.length; i' + top_100_list[i] + ''; } $mylist.html(top_100_li);

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 
     element  top_100_ul = '
      '; // This will store our entire unordered list for (var i=0, l=top_100_list.length; i' + top_100_list[i] + ''; } top_100_ul += '
    '; // Close our unordered list $mylist.replaceWith(top_100_ul);

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

反而,我们应该在父级侦听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
 }
});

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

8、消除查询浪费

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

你的全局JavaScript库看起来应该是这样的:

var mylib ={
 article_page : {
  init : function()  {
   // Article page specific jQuery functions. 
  }
 }, 
 traffic_light : {
  init : function()  {
   // Traffic light specific jQuery functions. 
  }
 }
}

9、遵从$(windows).load

有 一种诱惑会使jQuery开发者hook所有事情到 $(document).ready 这个虚伪的事件里。毕竟在大多数例子里都可以看到这样使用。虽然$(document).ready 非常有用,它在页面呈现时发生,虽然其它对象还在下载中。如果你发现你的页面在下载中停顿,就有可能是$(document).ready 引起的。你可以通过把jQuery functions帮定到$(window).load事件来减少下面下载时的CPU使用率,它是在所有HTML(包括iframe内容)都下载完以后才 去调用所有对象的。

$(window).load(function(){
 // jQuery functions to initialize after the page has loaded.
});

多余的功能,如拖拽、帮定可视化效果和动画、预读取图片等,使用这种方法比较好。

10、压缩JS

虽然和jQuery无关,但在这里也要提一下。使JavaScript函数和变量变得可读是一个趋势,这对开发者来讲是必不可少的,但对普通用户来 讲没有任何关系。不用什么借口,是时候把JS压缩纳入我们的工作流程中来了。注释你的代码,在投放到生产环境之前找一个压缩工具进行压缩。使用 YUICompressor 压缩你代码中多余的浪费的字节。根据我们的经验,它可以安全的把JavaScript压缩的尽可能小,而不会多占用CPU。小提示:为了在 YUICompressor里最大化压缩,应该这样这样定义变量(例如:var my_long_variable_name;)

学习和最有效的使用jQuery,最好的方法就是去查jQuery的文档和手册了。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

jQuery解析xml文件详解

jQuery内init构造器使用详解

The above is the detailed content of Summary of jQuery code performance optimization methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn