Home  >  Article  >  Web Front-end  >  Advanced tips for jquery performance optimization_jquery

Advanced tips for jquery performance optimization_jquery

WBOY
WBOYOriginal
2016-05-16 15:43:231219browse

Sometimes when we write jQuery, for the convenience of writing code, we often ignore the pressure brought to the client during program execution. Along with this comes problems such as slow running speed or even inability to run on some low-end browsers or low-end computers.

Therefore, it is necessary for us to optimize our own jquery code to achieve faster and smoother operation.

Advanced techniques for jquery performance optimization. The following mainly introduces jquery performance optimization from seven aspects:

1. Introduce jQuery library through CDN (Content Delivery Network)

2. Reduce DOM operations

3. Use native JS appropriately

4. Selector optimization

5. Caching jQuery objects

6. Define a reusable function

7. Use array method to traverse jQuery object collection

The specific instructions for each method are explained below:

Introducing the jQuery library through CDN (Content Delivery Network)

The simplest step to improve the performance of JavaScript in your website is to introduce the latest version of the jQuery library. The newly released version usually has better performance improvements and fixes some bugs. Or introducing it through CDN is also a good choice. Introduction through CDN can reduce the loading time of the website.

Here are some CDN services:

<!-- Case 1 - jQuery CDN -->
<script src="http://code.jquery.com/jquery-1.10.2.min.js" ></script>
<!-- Case 2 - requesting jQuery from Googles CDN (notice the protocol) -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<!-- Case 3 - requesting the latest minor 1.10.x version (only cached for an hour) -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10/jquery.min.js" ></script>
<!-- Case 4 - requesting the absolute latest jQuery version (use with caution) -->
<script src="http://code.jquery.com/jquery.min.js" ></script>

Some domestic CDN services:

http://www.bootcdn.cn/jquery/
<!--新浪 CDN-->
<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<!--百度 CDN-->
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<!--Bootstrap CDN-->
http://www.bootcdn.cn/jquery/

Reduce DOM operations

Although JavaScript performance has been greatly improved, DOM operations are still very resource-intensive, and DOM operations need to be reduced. This is especially important when inserting a large number of elements into a page.

For example:

<div id="elem" ></div>

// 不好的方式
//var elem = $('#elem');
//for(var i = 0; i < 100; i++){
// elem.append('<li>element '+i+'</li>');
//}
// 好的方式
var elem = $('#elem' ),
arr = [];
for(var i = 0; i < 100; i++){
arr. push('<li>element ' +i+'</li>' );
}
elem. append(arr. join('' ));

Caching all elements and inserting them once will improve performance because only one redraw of the page is triggered. The same is true for CSS style properties.

More reading: Front-end page stuck? It may be caused by DOM operations, you need to optimize the code

Use native JS appropriately

Creating jQuery objects brings some overhead. Therefore, if performance is more important, use native javascript as much as possible. In some ways it might be easier to understand and require less code to write. For example:

// 打印list中的li的id
$('#colors li' ). each(function(){
//将$(this).attr('id')方法替换为直接通过ID属性访问
console. log(this. id);
})

Selector Optimization

If you need better performance but still want to use jQuery, you can try some jQuery selector optimization. The following is a test program that records the execution time of different selectors through the browser's console console.time and console.timeEnd methods.

HTML:

<div id="peanutButter" >
<div id="jelly" class=".jellyTime" ></div>
</div>
JS:

//测试程序
var iterations = 10000,
  i;
//--------------------------------------------
//Case 1: 很慢
console.time('Fancy');
for (i = 0; i < iterations; i++) {
  $('#peanutButter div:first');
}
console.timeEnd('Fancy');
//--------------------------------------------
//Case 2: 比较好,但仍然很慢
console.time('Parent-child');
for (i = 0; i < iterations; i++) {
  $('#peanutButter div');
}
console.timeEnd('Parent-child');
//--------------------------------------------
//Case 3: 一些浏览器会比较快
console.time('Parent-child by class');
for (i = 0; i < iterations; i++) {
  // 通过后代Class选择器
  $('#peanutButter .jellyTime');
}
console.timeEnd('Parent-child by class');
//--------------------------------------------
//Case 4: 更好的方式 
console.time('By class name');
21
for (i = 0; i < iterations; i++) {
  // 直接通过Class选择器
  $('.jellyTime');
}
console.timeEnd('By class name');
//--------------------------------------------
//Case 5: 推荐的方式 ID选择器
console.time('By id');
for (i = 0; i < iterations; i++) {
  $('#jelly');
}
console.timeEnd('By id');

Execution result:

Caching jQuery objects

Every time a new jQuery object is constructed through a selector, the Sizzle engine at the core of jQuery will traverse the DOM and match the real dom element through the corresponding selector. This method is relatively inefficient. In modern browsers, you can use the document.querySelector method to match the corresponding element by passing in the corresponding Class parameter. However, versions below IE8 do not support this method. One practice to improve performance is to cache jQuery objects via variables. For example:

<ul id="pancakes" >
     <li>first</li>
     <li>second</li>
     <li>third</li>
     <li>fourth</li>
     <li>fifth</li>
</ul>

JS:

// 不好的方式:
// $('#pancakes li').eq(0).remove();
// $('#pancakes li').eq(1).remove();
// $('#pancakes li').eq(2).remove();
// ------------------------------------
// 推荐的方式:
var pancakes = $('#pancakes li');
pancakes.eq(0).remove();
pancakes.eq(1).remove();
pancakes.eq(2).remove();
// ------------------------------------
// 或者:
// pancakes.eq(0).remove().end()
// .eq(1).remove().end()
// .eq(2).remove().end();

Define a reusable function

Go directly to the example:

HTML:
<button id="menuButton" >Show Menu!</button>
<a href="#" id="menuLink" >Show Menu!</a>

JS:

//Bad: 
//这个会导致多个回调函数的副本占用内存
$('#menuButton, #menuLink' ). click(function(){
// ...
});
//----------------------------------------------
//Better
function showMenu(){
alert('Showing menu!' );
// Doing something complex here
}
$('#menuButton' ). click(showMenu);
$('#menuLink' ). click(showMenu);

If you define an inline callback function with a jQuery object containing multiple elements (as in the first example above), a callback function will be saved in memory for each element in the collection. copy of.

Use array method to traverse jQuery object collection

You may not have noticed, but this elegant implementation of the jQuery each method comes at a cost in terms of performance. There is a faster way to iterate over a jQuery object. It is implemented through an array. The jQuery object collection is an array-like object with length and value attributes. You can test the performance through the program:

HTML:

<ul id="testList" >
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li> 
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <!-- add 50 more -->
</ul>

JS:

var arr = $('li'),
  iterations = 100000;
//------------------------------
// Array实现:  
console.time('Native Loop');
for (var z = 0; z < iterations; z++) {
  var length = arr.length;
  for (var i = 0; i < length; i++) {
    arr[i];
  }
}
console.timeEnd('Native Loop');
//------------------------------
// each实现:  
console.time('jQuery Each');
for (z = 0; z < iterations; z++) {
  arr.each(function(i, val) {
    this;
  });
}
console.timeEnd('jQuery Each');

Result:

You can see that traversal through array implementation has higher execution efficiency.


//------------------------------------------------ -------Continuous updates...

The above is a summary of some collected knowledge. If you have any suggestions or questions, please leave a message for discussion.

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