jquery Best Practices Complete article _jquery

Source: Internet
Author: User
Tags versions

Last week, I organized the idea of jquery design.

The article is an introductory tutorial that explains "How to use jquery"from the perspective of design thinking. Today's article goes a step further and explains "How to use jquery well".

My main reference is the Addy Osmani ppt "Tips for improving jquery performance" (jquery Proven performance tips and Tricks). He is a member of the jquery development team, with a certain authority, the conclusions presented are supported by test data, very valuable.

==============================================

jquery Best Practices

Nanyi Finishing

1. Use the latest version of jquery

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

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

$ ('. Elem ')

$ ('. Elem ', context)

Context.find ('. Elem ')

We use the 1.4.2, 1.4.4, 1.6.23 version of the jquery test to see how many times the browser can execute in 1 seconds. The results are as follows:

As you can see, the 1.6.2 version runs much more than two old versions. In particular, the first statement, performance has several times the improvement.

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

2. Use pair Selector

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

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

For example, the following statement has the best performance:

$ (' #id ')

$ (' form ')

$ (' input ')

When these selectors are encountered, the native methods of the browser (such as getElementById ()) are automatically invoked within jquery, so they perform faster.

(2) Slower selector: class selector

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

Firefox, Safari, Chrome, opera browsers all have native method 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 attribute selector

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

$ (': Hidden ')

The example of a property selector is:

$ (' [Attribute=value] ')

The two statements are the slowest, because browsers do not have native methods for them. However, the new versions of some browsers add the Queryselector () and Queryselectorall () methods, which can greatly improve the performance of such selectors.

Finally, the performance comparison chart of different selectors.

As you can see, the ID selector is 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 the 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 see it in one 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 can result in a certain performance penalty. It's 5%-10% slower than the fastest form.

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

This is the quickest statement. The find () method invokes the browser's native method (Getelementbyid,getelementbyname,getelementbytagname, and so on), so it is 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 uses the sizzle engine internally to handle various selectors. The sizzle engine's selection order is right-to-left, so this statement is first selected. Child, and then filter 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 one selects only the direct child element, which can be used to select a multilevel child element, so it is slower, probably 77% slower than the fastest form.

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

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

Therefore, the best choice is $parent.find ('. Child '). Moreover, since $parent is often generated in the previous operation, jquery caches it, thus further speeding up the execution speed.

Specific examples and comparison results, please see here.

4. Do not use jquery too much

jquery is faster than native JavaScript methods. So there are occasions where native methods can be used, as far as possible to avoid using jquery.

Take a look at the example below, and bind a function to handle the click event for a element:

$ (' a '). Click (function () {

    Alert ($ (this). attr (' id '));

});

What this code means is that when you click a element, the id attribute of the element pops up. In order to get this property, you must call jquery twice in succession, the first time is $ (this), and the second is attr (' id ').

In fact, this kind of treatment is completely unnecessary. The more correct way is to use the JavaScript native method directly to invoke This.id:

$ (' a '). Click (function () {

    alert (this.id);

});

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

5. Do the cache

Selecting a page element is a costly step. Therefore, the number of times you should use selectors should be as small as possible, and you can cache the selected results as much as you can for later reuse.

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

JQuery (' #top '). Find (' P.classa ');

JQuery (' #top '). Find (' P.CLASSB ');

A better way to do this is to:

  var cached = JQuery (' #top ');

Cached.find (' P.classa ');

Cached.find (' P.CLASSB ');

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

6. Use chain style

One of the great features of jquery is that it allows the use of chain notation.

$ (' div '). Find (' H3 '). EQ (2). html (' Hello ');

When using chain style, jquery automatically caches the results of each step, so it is faster than the non-chain style. According to the test, the chain-type writing is about 25% faster than the non-chained style (not using the cache).

7. Delegate processing of events (event delegation)

The JavaScript event model, in "bubbling" mode, in other words, the child element's events are progressively "bubbling" 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), which has 100 lattice (TD Element), now requires a click on each grid to bind a hit event (click), please do not need to execute the following command 100 times?

$ ("TD"). BIND ("click", Function () {

$ (this). Toggleclass ("click");

});

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

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

There are two specific ways of writing. The first is the use of the. Delegate () Method:

$ ("table"). Delegate ("TD", "click", Function () {

$ (this). Toggleclass ("click");

});

The second is the use of the. Live () Method:

$ ("table"). each (function () {

$ ("TD", this). Live ("Click", Function () {

$ (this). Toggleclass ("click");
});
});

These two kinds of writing are basically equivalent. The only difference is that. Delegate () is triggered when the event bubbles to the specified parent element,. Live () is triggered when the event bubbles to the root element of the document, so. Delegate () is slightly faster than live (). In addition, the two methods have the advantage over the traditional. Bind () method, which is also valid for dynamically inserted elements,. bind () is valid only for existing DOM elements and not for dynamically inserted elements.

According to the test, the delegate processing is dozens of times times faster than no delegate processing. In the case of delegate processing,. Delegate () is about 26% faster than. Live ().

8. Change the DOM structure less

(1) Changing the DOM structure is expensive, so do not use it frequently. Append (),. insertbefore () and. Insetafter ().

If you want to insert multiple elements, merge them first, and then insert them once more. According to the test, the merge inserts are nearly 10 times times faster than without merging inserts.

(2) If you want to do a lot of work on a DOM element, you should first use the. Detach () method, take this element out of the DOM, process it, and then plug it back into the document. According to the test, using the. Detach () method is 60% faster than when not used.

(3) If you want to store data on a DOM element, do not write the following:

var elem = $ (' #elem ');

  Elem.data (Key,value);

But to write

var elem = $ (' #elem ');

  $.data (Elem,key,value);

According to the test, the latter type of writing is nearly 10 times times faster than the previous wording. 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. (Refer to the 10th below.) )

9. Handle loops correctly

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, which are faster than jquery's. each () method, should use the native method preferentially.

10. Generate as few jquery objects as possible

Whenever you use a selector (such as $ (' #id '), a jquery object is generated. The jquery object is a very large object, with many attributes and methods, and it takes up a lot of resources. So, try to build a jquery object as little as possible.

For example, many jquery methods have two versions, one for the jquery object and the other for the jquery function . The following two examples are the text that takes out an element, using the text () method. You can use a version of the jquery object:

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

  var $ts = $text. Text ();

You can also use a version of the jquery function:

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

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

Since the latter version of the jquery function does not operate through the jquery object, the relative overhead is smaller and faster.

Finish

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.