jquery Performance Optimization Techniques Analysis _jquery

Source: Internet
Author: User
Tags modifier javascript array

In this paper, jquery performance optimization techniques are analyzed in detail. Share to everyone for your reference. The specific analysis is as follows:

First, use the latest version of the jquery class library

The new jquery version will be bug fixes and optimizations over the previous version, but be aware that after replacing the version, don't forget to test your code, which is sometimes not completely backwards compatible.

Second, use the appropriate selector

The best and worst way to perform the jquery selector is as follows:

ID selector, such as $ (' #id ', context)
Tag Selector, such as $ (' P ', context)
Class selector, such as $ ('. class ', context)
Property selector, such as $ (' [Attribute=value] ', context)
Pseudo class selector, such as $ (': hidden ', context)

Supplementary and Precautions:

You can narrow the scope of the positioning element by assigning context contexts to the selector as much as possible
Avoid ID repeat modifier ID, error code: var $el = $ (' #list #item1 ')
Avoid tags or class modifier ids, error codes: var $el = $ (' ul #item1 ')
If you use the property selector, try to specify the tag selector that you belong to, which speeds up access, the correct code: var $el = $ (' a[title= "link] ')

Third, cache objects

The following are the bad performance ways:

$ (' #home '). CSS (...);
$ (' #home '). Bind (' click ', Function () {});
$ (' #home '). addclass (...);

Description: JQuery finds the DOM, consumes time and performance during the process of creating each selector.

The better way:

var $homeLink = $ (' #home ', context);
$homeLink. CSS (...);
$homeLink. Bind (' click ', Function () {});
$homelink. addclass (...);

Description: Never let the same selector appear more than once in your code.

Dom operations at the time of the loop

Using jquery makes it easy to add, delete, or modify DOM nodes, but in some loops, such as for (), while (), or $.each (), there is an example to be noted:

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

Description: Loop add Li node 100 times, this operation consumes the performance is not low, so the better way is to add the node before inserting the DOM tree all created, and then added to the DOM tree. A better way:

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

Five, array mode using the jquery object

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

Also note: Checking length is a way to check if the jquery object exists.

var $list = $ (' #list ');
if ($list) {  //always True
  //do something
}
if ($list. Length) {//Owning element returns true
  //do something
}

VI. Event Agent

Each JavaScript event, such as Click,mouseover, bubbles to the parent node. This can be 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 $item 1 = $ (' #item1 '),
  $item 2 = $ (' #item2 '),
  $item 3 = $ (' #item3 ');
  ...

$item 1.click (function () {...});
$item 2.click (function () {...});
$item 3.click (function () {...});
...

Description: This way, if there are 100 Li, to bind 100 events. Obviously, unscientific, a lot of performance loss.

A better way to do this is to just bind an event to Li's parent, and then get to the current element of the click by Event.target.

var $list = $ (' #list ');
$list. Click (function (e) {
  var $currentItem = $ (e.target);  E.target captures the target element of the current triggering event
  ...
};

Seven, convert your code into a jquery plugin

If you're spending time writing similar jquery code each time, consider turning this part of the code into a plug-in that will make your code more reusable and help you organize your code effectively.

Use JavaScript array join () to stitch strings

When working with long strings, using the Join () method helps optimize performance.

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

Nine, reasonable use of HTML5 data property

The Data property of HTML5 can help us to insert the information, especially the data exchange at the front and back. The data () method of jquery, effectively utilizes the HTML5 's attribute, to obtain the information automatically.

...
<a id= "Info" data-info-index= "data-role=" "LinkInfo" ></a> ...

var $infoLink = $ (' #info ');
var infoindex = $infoLink. Data (' Info-index ');
var type = $infoLink. Data (' LinkInfo ');

Ten, try to use native JavaScript method

Such as:

$ (this). CSS (' Color ': ' Blue ');

Optimized into:

This.style.color = ' Blue ';

Such as:

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

Optimized into:

$ (document.createelement (' P '));

Xi. compressed JavaScript

Use the compression tool to compress JavaScript files.
When you publish an item, you should use the compressed version JavaScript file.

I hope this article will help you with your jquery programming.

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.