Home > Web Front-end > JS Tutorial > Analysis of jQuery performance optimization techniques_jquery

Analysis of jQuery performance optimization techniques_jquery

WBOY
Release: 2016-05-16 16:13:25
Original
1163 people have browsed it

This article analyzes jQuery performance optimization techniques in more detail. Share it with everyone for your reference. The specific analysis is as follows:

1. Use the latest version of jQuery class library

The new version of jQuery will have bug fixes and some optimizations compared to the previous version. However, it should be noted that after changing the version, don’t forget to test your code. After all, sometimes it is not fully backwards compatible.

2. Use appropriate selectors

The best to worst performance of jQuery selectors is as follows:

id selector, such as $('#id', context)
Tag selector, such as $('p', context)
class selector, such as $('.class', context)
Attribute selector, such as $('[attribute=value]', context)
Pseudo-class selector, such as $(':hidden', context)

Supplementary and Notes:

Try to specify context for the selector to narrow the scope of positioned elements
Avoid repeated modification of id. Error code: var $el = $('#list #item1')
Avoid tags or classes modifying ids, error code: var $el = $('ul #item1')
If you use an attribute selector, try to specify the tag selector to speed up access. Correct code: var $el = $('a[title="link"]')

3. Cache object

Here’s how to perform poorly:

$('#home').css(...);
$('#home').bind('click', function() {});
$('#home').addClass(...);
Copy after login

Note: jQuery will search the DOM during the process of creating each selector, consuming time and performance.

Better way:

var $homeLink = $('#home', context);
$homeLink.css(...);
$homeLink.bind('click', function() {});
$homelink.addClass(...);
Copy after login

Note: Never let the same selector appear multiple times in your code.

4. DOM operation during loop

Using jQuery, you can easily add, delete or modify DOM nodes, but when processing nodes in some loops, such as for(), while() or $.each(), there is an example below that deserves your attention:

var $list = $('#list');
for(var i = 0; i < 100; i++) {
  $list.append('<li>' + i + '</li>');
}
Copy after login

Note: Add li nodes 100 times in a loop. This operation consumes a lot of performance, so a better way is to create all the nodes to be added before inserting them into the DOM tree, and then add them to the DOM tree at once. Better way:

var $list = $('#list'),
  fragment = '';
for(var i = 0; i < 100; i++) {
  fragment += '<li>' + i + '</li>';
}
$list.append(fragment);
Copy after login

5. Using jQuery objects in array

Use jQuery selector to get the result which is a jQuery object. In terms of performance, it is recommended to use a simple for or while loop instead of $.each(), which can make your code faster.

Also note: Checking length is a way to check whether a jQuery object exists.

var $list = $('#list');
if($list) {  //总是true
  //do something
}
if($list.length) { //拥有元素才返回true
  //do something
}
Copy after login

6. Event Agent

Every JavaScript event (such as click, mouseover) will bubble up to the parent node. This is useful when we need to call the same function on multiple elements.

...
<ul id="list">
  <li id="item1"></li>
  <li id="item2"></li>
  <li id="item3"></li>
  ...
</ul>
...

var $item1 = $('#item1'),
  $item2 = $('#item2'),
  $item3 = $('#item3');
  ...

$item1.click(function() {...});
$item2.click(function() {...});
$item3.click(function() {...});
...
Copy after login

Note: In this way, if there are 100 li, 100 events will be bound. Obviously, it is unscientific and causes a lot of performance loss.

A better way is: just bind an event to the parent node ul of li once, and then get the current element clicked through event.target.

var $list = $('#list');
$list.click(function(e) {
  var $currentItem = $(e.target);  //e.target捕捉到当前触发事件的目标元素
  ...
});
Copy after login

7. Convert your code into jQuery plug-in

If you spend time writing similar jQuery code every time, you can consider turning this similar code into a plug-in, which can make your code more reusable and can effectively help you organize your code. .

8. Use Javascript array join() to splice strings

When processing long strings, using the join() method helps optimize performance.

var arr = [];
for(var i = 0; i < 100; i++){
  arr[i] = '<li>' + i + '</li>';
}
$list.html(arr.join(''));
Copy after login

9. Reasonable use of HTML5 data attributes

The data attribute of HTML5 can help us insert data, especially the data exchange between the front and back ends. jQuery's data() method effectively uses HTML5 attributes to automatically obtain data.

...
<a id="info" data-info-index="23" data-role="linkInfo"></a>
...

var $infoLink = $('#info');
var infoIndex = $infoLink.data('info-index');
var type = $infoLink.data('linkInfo');
Copy after login

10. Try to use native JavaScript methods

For example:

$(this).css('color': 'blue');
Copy after login

Optimized to:

this.style.color = 'blue';
Copy after login

For example:

$('<p></p>');
Copy after login

Optimized to:

$(document.createElement('p'));
Copy after login

11. Compress JavaScript

Compress JavaScript files using a compression tool.
When publishing your project, you should use a "minified" version of your JavaScript files.

I hope this article will be helpful to everyone’s jQuery programming.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template