jquery Performance Optimization

Source: Internet
Author: User

The version of jquery is updated quickly and you should always use the latest version. Because the new version will improve performance, there are many more features.

Here's a look at how different versions of jquery performance differ. Here are the three most common jquery selection statements:

 
$ ('. Elem ') $ ('. Elem ', context) Context.find ('. Elem ')

We tested with 1.4.2, 1.4.4, 1.6 and 23 versions of jquery to see how many times the browser could execute in 1 seconds. The results are as follows:

As you can see, 1.6. Version 2 runs, far more than two old versions. Especially in the first statement, performance is increased several times.

Tests for other statements, such as. attr ("value") and. Val (), are also new versions of jquery that perform better than the old version.

2. Using the pair selector

In jquery, you can select the same page element with a variety of selectors. The performance of each selector is different, and you should be aware of their performance differences.

(1) Fastest selector: ID selector and element tag Selector

For example, the following statement performs best:

    $(‘#id‘)   $(‘form‘)  $(‘input‘)

When these selectors are encountered, jquery internally automatically calls the browser's native methods (such as getElementById ()), so they execute faster.

(2) Slower selector: class selector

The performance of $ ('. ClassName ') depends on the different browsers.

Firefox, Safari, Chrome, opera browsers have native methods Getelementbyclassname (), so the speed is not slow. However, IE5-IE8 does not deploy this method, so this selector will be quite slow in IE.

(3) Slowest selector: Pseudo class selector and property selector

Let's look at examples first. To find out all the hidden elements in a Web page, use the Pseudo-class selector:

$(‘:hidden‘)

The example of the property selector is:

$(‘[attribute=value]‘)

These two statements are the slowest because the browser does not have a native method for them. However, the new version of some browsers adds the Queryselector () and Queryselectorall () methods, which can significantly improve the performance of such selectors.

Finally, the performance comparison of different selectors is shown.

As you can see, the ID selector is far ahead, then the tag Selector, the third is the class selector, and the other selectors are very slow.

3. Understanding the relationship between child elements and parent elements

The following six selectors select child elements from a parent element. Do you know which speed is the fastest and which is the slowest?

    $(‘.child‘, $parent)  $parent.find(‘.child‘)  $parent.children(‘.child‘)  $(‘#parent > .child‘)  $(‘#parent .child‘)  $(‘.child‘, $(‘#parent‘))

Let's look at it in a sentence.

(1) $ ('. Child ', $parent)

This statement means that a DOM object is given, and then a child element is selected from it. jquery automatically turns this statement into $.parent.find (' child '), which results in a certain performance penalty. It is 5%-10% slower than the fastest form.

(2) $parent. Find ('. Child ')

This is the fastest statement: the Find () method invokes the browser's native method (Getelementbyid,getelementbyname,getelementbytagname, and so on), so it's faster

(3) $parent. Children ('. Child ')

Within jquery, this statement iterates through the nodes using the $.sibling () and JavaScript nextsibling () methods. It is about 50% slower than the fastest form.

(4) $ (' #parent >. Child ')

jquery internally uses the sizzle engine to handle a variety of selectors. The sizzle engine is selected from right to left, so this statement is selected first. Child, and then filters out the parent element #parent, which causes it to be about 70% slower than the fastest form.

(5) $ (' #parent. Child ')

This statement is the same as the previous one. However, the previous bar selects only the immediate child element, which can be used to select a multilevel sub-element, so it is slower and probably 77% slower than the fastest form.

(6) $ ('. Child ', $ (' #parent '))

Within jquery, this statement is converted to $ (' #parent '). Find ('. Child '), which is 23% slower than the fastest form.

Therefore, the best choice is $parent.find ('. Child '). Furthermore, because $parent often has been generated in the previous operations, jquery caches it, so the execution speed is further accelerated.

For specific examples and comparison results, see here.

4. Do not use jquery too much

jquery is no faster and can be compared to native JavaScript methods. So there are native methods that can be used in situations where try to avoid using jquery.

With the simplest selector, document.getElementById ("foo") is 10 times faster than $ ("#foo").
Another example is to bind a element to a function that handles the Click event:

    $(‘a‘).click(function(){    alert($(this).attr(‘id‘));  });

This code means that after clicking the a element, the id attribute of the element pops up. In order to get this property, jquery must be called twice in succession, the first is $ (this), and the second is attr (' id ').

In fact, such treatment is completely unnecessary. The more correct way to do this is to use the JavaScript native method directly, calling This.id:

    $(‘a‘).click(function(){    alert(this.id);  });

According to the test, this.id speed is more than 20 times faster than $ (this). attr (' id ').

5. Do the Caching

Selecting a page element is a costly step. Therefore, you should use selectors as few times as possible, and cache the selected results as much as you want, so that you can reuse them later.

For example, the following is a bad way to do this:

    jQuery(‘#top‘).find(‘p.classA‘);  jQuery(‘#top‘).find(‘p.classB‘);

A better notation is:

    var cached = jQuery(‘#top‘);  cached.find(‘p.classA‘);  cached.find(‘p.classB‘);

According to the test, the cache is 2-3 times faster than no cache.

6. Use chained notation

One of the major features of jquery is that it allows you to use chained notation.

$(‘div‘).find(‘h3‘).eq(2).html(‘Hello‘);

When using chained notation, jquery automatically caches the results of each step, so it is faster than non-chained notation. Depending on the test, the chained notation is about 25% faster than the non-chained notation (without using the cache).

7. Delegate handling of events (event delegation)

The JavaScript event model, in "bubbling" mode, in other words, the child element's events are "bubbling up" to become the parent element's event.

With this, you can greatly simplify the binding of events. For example, there is a table (table element) with 100 squares (TD elements), which now requires a click event to be bound on each grid (click), do I need to execute the following command 100 times?

    $("td").on("click", function(){    $(this).toggleClass("click");  });

The answer is no, we just have to bind this event to the table element, because after the click event of the TD element, the event will "bubble" to the parent element table and be heard.

Therefore, this event only needs to be bound to the parent element 1 times, without having to bind the child element 100 times, thereby greatly improving performance. This is called the "delegate Processing" of the event, which is the child element "delegate" The parent element handles the event.

    $("table").on("click", "td", function(){    $(this).toggleClass("click");  });

A better notation is to bind events to the Document object.

    $(document).on("click", "td", function(){    $(this).toggleClass("click");  });

If you want to cancel the binding of an event, use the Off () method.

$(document).off("click", "td");
8. Change the DOM structure less
    1. Changing the DOM structure is expensive, so do not use the. Append (),. InsertBefore (), and. Insetafter () methods frequently. If you want to insert multiple elements, merge them first, and then insert them once. According to the test, the merge insert is nearly 10 times times faster than not merging inserts.
    2. If you want to do a lot of processing of a DOM element, you should first use the. Detach () method to take this element out of the DOM, after processing, and then back into the document. According to the test, the use of the. Detach () method is 60% faster than when not in use.
    3. If you want to store data on DOM elements, do not write the following:

          var elem = $(‘#elem‘);  elem.data(key,value);

      and to write

          var elem = $(‘#elem‘);  $.data(elem[0],key,value);

      According to the test, the latter is nearly 10 times times faster than the previous one. Because the Elem.data () method is defined above the prototype object of the jquery function, and the $.data () method is defined above the jquery function, the call is not invoked from a complex jquery object, so it is much faster. (see 10th below.) )

    4. When inserting HTML code, the browser's native innterhtml () method is faster than the HTML () of the JQuery object.

9. Proper handling of loops

Loops are always a time-consuming operation, and if you can use complex selectors to select elements directly, do not use loops to identify elements.

JavaScript native loop methods for and while are faster than JQuery's. each () method, you should prioritize using native methods.

10. Create as few jquery objects as possible

Whenever you use a selector (such as $ (' #id ')), a jquery object is generated. The jquery object is a huge object with many properties and methods that can take up a lot of resources. Therefore, create as few jquery objects as possible.

For example, many jquery methods are available in two versions, one for jquery objects, and the other for jquery functions. The following two examples are the text that takes out an element, and all that is used is the literal () method.

You can use both versions of the jquery object:

    var $text = $("#text");  var $ts = $text.text();

You can also use the version for the jquery function:

   var $text = $("#text");  var $ts = $.text($text);

Because the latter version of the jquery function does not operate through jquery objects, the relative overhead is relatively small and faster.

11. Select the shortest method for the scope chain

Strictly speaking, this rule applies to all JavaScript programming, not just jquery.

We know that JavaScript variables take a chain scope. When reading a variable, look for the variable in the current scope and, if it is not found, go to the scope of the previous level to look for the variable. Such a design makes it much faster to read local variables than to read global variables.

Take a look at the following two code, the first code reads global variables:

    var a = 0;  function x(){    a += 1;  }

The second piece of code reads the local variable:

    function y(){    var a = 0;    a += 1;  }

The second code reads variable a without going to the previous scope, so it is five or six times times faster than the first code.

Similarly, when invoking an object method, the closure mode is faster than the prototype mode.

Prototype mode:

    var X = function(name){ this.name = name; }  X.prototype.get_name = function() { return this.name; };

Closure Mode:

    var Y = function(name) {    var y = { name: name };    return { ‘get_name‘: function() { return y.name; } };  };

Also the Get_name () method, closure mode is faster.

12. Managing Events using Pub/sub mode

When an event occurs, if you want to perform multiple operations consecutively, it is best not to write the following:

    function doSomthing{    doSomethingElse();    doOneMoreThing();  }

Instead, use the event-triggered form:

    function doSomething{    $.trigger("DO_SOMETHING_DONE");  }  $(document).on("DO_SOMETHING_DONE", function(){    doSomethingElse(); }  );

You can also consider using the deferred object.

    function doSomething(){    var dfd = new $.Deferred();    //Do something async, then...     //dfd.resolve();    return dfd.promise();  }  function doSomethingElse(){    $.when(doSomething()).then(//The next thing);  }
Additional knowledge points supplementing the use of the Hungarian nomenclature

Prefix the variable with $ to make it easy to identify the jquery object.

    // 糟糕    var first = $(‘#first‘);    var second = $(‘#second‘); var value = $first.val(); // 建议 - 在jQuery对象前加$前缀 var $first = $(‘#first‘); var $second = $(‘#second‘), var value = $first.val();
Using the var chain (single var mode)
var  $first = $(‘#first‘),  $second = $(‘#second‘), value = $first.val(), k = 3, cookiestring = ‘SOMECOOKIESPLEASE‘, i, j, myArray = {};
Please use ' on '

In the new version of jquery, Shorter on ("click") is used to replace functions like Click (). In the previous version, on () is bind (). Since the jquery 1.7 release, ON ()? The preferred method for attaching event handlers. However, for consistency reasons, you can simply use the on () method.

Bad$first. Click (function(){$first. CSS (' Border ',' 1px solid red ');$first. CSS (' Color ',' Blue ');$first. Hover (function(){ $first. css ( ' border ',  1px solid Red ');}) //recommended  $first. On ( ' click ', function () {  $first. css ( ' border ',  1px solid Red ');  $first. css ( ' color ',  ' Blue ');})  $first. On ( ' hover ', function () { $first. CSS (  ' 1px solid red ');       
Select short-Circuit evaluation

A short-circuit evaluation is an expression that evaluates from left to right, with && (logical AND) or | | (logical OR) operators.

// 糟糕function initVar($myVar) { if(!$myVar) { $myVar = $(‘#selector‘); }}// 建议function initVar($myVar) { $myVar = $myVar || $(‘#selector‘);}

原文链接:http://www.ruanyifeng.com/blog/2011/08/jquery_best_practices.html

JQuery Performance Optimization

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.