JQuery performance optimization skills analysis, jquery performance optimization skills

Source: Internet
Author: User
Tags javascript array

JQuery performance optimization skills analysis, jquery performance optimization skills

This article gives a detailed analysis of jQuery performance optimization techniques. Share it with you for your reference. The specific analysis is as follows:

I. Use the latest jQuery class library

The new version of jQuery will fix bugs and optimize bugs compared with the previous version. However, after changing the version, do not forget to test your code. After all, sometimes it is not completely backward compatible.

2. Use a proper Selector

The best-to-worst-performing jQuery selector method 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 $ (': Den den', context)

Supplements and precautions:

Specify the context for the selector to narrow down the scope of the positioning element.
Avoid duplicate id modification by id. Error code: var $ el = $ ('# list # item1 ')
Avoid modifying the id by label or class. Error code: var $ el = $ ('ul # item1 ')
If you use the attribute selector, specify the tag selector to accelerate access. The correct code is var $ el =$ ('a [title = "link"] ').

Iii. cache objects

The following is a poor performance method:

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

Note: jQuery searches for the DOM and consumes time and performance when creating each selector.

Better method:

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

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

Iv. DOM operations during Loops

JQuery allows you to easily add, delete, or modify DOM nodes, but in some loops, such as for (), while (), or $. when processing nodes in each (), the following instance is worth your attention:

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

Note: adding li nodes cyclically for 100 times consumes less performance, so it is better to create all the nodes to be added before inserting the DOM tree, and then add it to the DOM tree. Better Way:

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

5. Use jQuery objects in Arrays

Using the jQuery selector to obtain the result is a jQuery object. In terms of performance, we recommend that you use a simple for or while loop instead of $. each () to make your code faster.

Note: checking the length is a way to check whether a jQuery object exists.

Var $ list = $ ('# list'); if ($ list) {// always true // do something} if ($ list. length) {// returns true only when the specified element exists. // do something}

Vi. Event proxy

Every JavaScript event (such as click and mouseover) will bubble to the parent node. This is useful when we need to call the same function for 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() {...});...

Note: if there are 100 li events, bind 100 events. Obviously, it is not scientific, and the performance suffers a lot of losses.

A better way is to bind the event to the li's parent node. Then, use event.tar get to get the current element.

Var $ list = $ ('# list'); $ list. click (function (e) {var $ currentItem = triggers (e.tar get); // e.tar get captures the target element of the currently triggered event ...});

7. Convert your code into a jQuery plugin

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

8. concatenate strings using Javascript Array join ()

When processing long strings, the join () method is used to optimize the performance.

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

9. Make Rational Use of HTML5 data attributes

The data attribute of HTML5 can help us insert data, especially data exchange at the front and back ends. JQuery's data () method 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');

10. Try to use the native JavaScript Method

For example:

$(this).css('color': 'blue');

Optimized:

this.style.color = 'blue';

For example:

$('<p></p>');

Optimized:

$(document.createElement('p'));

11. Compress JavaScript

Use a compression tool to compress JavaScript files.
When releasing a project, use the "compressed version" JavaScript file.

I hope this article will help you with jQuery programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.