JQuery Best Practices

Source: Internet
Author: User

This article mainly references Addy Osmani's PPT "How to Improve jQuery's Performance" (jQuery Proven Performance Tips And Tricks ). He is a member of the jQuery development team and has a certain degree of authority. His conclusions are all supported by test data, which is very valuable.
1. Use the latest version of jQuery
JQuery is updated quickly. You should always use the latest version. Because the new version improves performance and has many new features.
Let's take a look at the differences in jQuery performance in different versions. Here are the three most common jQuery selection statements:
$ ('. Elem ')
$ ('. Elem', context)
Context. find ('. elem ')
We use jQuery tests in versions 1.4.2, 1.4.4, and 1.6.2 to see how many times the browser can execute within 1 second. The result is as follows:


We can see that version 1.6.2 runs much more than two old versions. In particular, the first statement improves the performance several times.
Testing of other statements, such as. attr ("value") and. val (), is also a new version of jQuery, which is better than the old version.
2. Use the pair Selector
In jQuery, you can use multiple selectors to select the same webpage element. The performance of each selector is different. You should understand their performance differences.
(1) The fastest selector: id selector and element tag Selector
For example, the following statements have the best performance:
$ ('# Id ')
$ ('Form ')
$ ('Input ')
When these selectors are encountered, jQuery automatically calls the native method of the browser (such as getElementById (), so their execution speed is fast.
(2) Slow selector: class selector
The performance of $ ('. classname') depends on different browsers.
Firefox, Safari, Chrome, and operabrowsers all have native Methods getElementByClassName (), so the speed is not slow. However, the 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 take a look at the example. To find all the hidden elements on a webpage, the pseudo-class selector is required:
$ (': Den den ')
The following is an example of an attribute selector:
$ ('[Attribute = value]')
These two statements are the slowest, because the browser does not have a native Method for them. However, in some new versions of browsers, The querySelector () and querySelectorAll () methods are added, which greatly improves the performance of such selectors.
Finally, we will compare the performance of different selectors.

 

We can see that the ID selector is far ahead, then the tag selector, and the third is the Class selector. Other selectors are very slow.
3. Understand the relationship between child and parent Elements
The following six selectors select child elements from the parent element. Do you know which 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 the sentence.
(1) $ ('. child', $ parent)
This statement specifies a DOM object and then selects a child element from it. JQuery will automatically convert this statement into $. parent. find ('child '), which will cause some performance loss. It is 5%-10% slower than the fastest form.
(2) $ parent. find ('. child ')
This is the fastest statement .. The find () method calls the browser's native method (getElementById, getElementByName, getElementByTagName, and so on), so the speed is faster.
(3) $ parent. children ('. child ')
In jQuery, this statement uses the $. sibling () and javascript nextSibling () Methods to traverse nodes one by one. It is about 50% slower than the fastest form.
(4) $ ('# parent>. child ')
JQuery uses the Sizzle engine internally to process various selectors. The sequence of Sizzle engine selection is from right to left, so this statement is selected first. child, and then filter out the parent element # parent one by one, which causes it to be about 70% slower than the fastest form.
(5) $ ('# parent. child ')
This statement is the same as the previous statement. However, the previous one only selects direct sub-elements. This one can be used to select multi-level sub-elements, so it is slower, probably 77% slower than the fastest form.
(6) $ ('. child', $ ('# parent '))
JQuery converts this statement into $ ('# parent'). find ('. child'), which is 23% slower than the fastest format.
Therefore, the best choice is $ parent. find ('. child '). In addition, because $ parent is often generated in the previous operation, jQuery will cache it, which further speeds up the execution.
For specific examples and comparison results, see here.
4. Do not over-use jQuery
JQuery is faster and cannot be compared with the native javascript method. Therefore, when there are scenarios where native methods can be used, avoid using jQuery whenever possible.
See the following example to bind a function for processing click events for element:
$ ('A'). click (function (){
Alert ($ (this). attr ('id '));
});
The code in this section means that after clicking Element a, the id attribute of the element is displayed. To obtain this attribute, jQuery must be called twice in a row. The first is $ (this), and the second is attr ('id ').
In fact, such processing is completely unnecessary. A more correct method is to directly use the javascript native method to call this. id:
$ ('A'). click (function (){
Alert (this. id );
});
According to the test, this. id is more than 20 times faster than $ (this). attr ('id.
5. cache well
Selecting a webpage element is costly. Therefore, the fewer selector times, the better, and cache the selected results as much as possible to facilitate future use.
For example, the following statement is a bad one:
JQuery ('# top'). find ('p. classA ');
JQuery ('# top'). find ('p. classB ');
Better Syntax:
Var cached = jQuery ('# top ');
Cached. find ('p. classA ');
Cached. find ('p. classB ');
According to the test, the cache speed is 2-3 times faster than that without caching.
6. use chaining
A major feature of jQuery is that it allows the use of chained writing.
Certificate ('div'0000.find('h3'0000.eq(2).html ('hello ');
When Using Chained writing, jQuery automatically caches the results of each step, so it is faster than non-chained writing. According to tests, chained writing is about 25% faster than non-chained writing (without caching.
7. Event Delegation)
The javascript event model adopts the "bubble" mode. That is to say, the subelement event is "Bubbling" step by step to become the parent element event.
This can greatly simplify event binding. For example, there is a table (table element) with 100 grids (td element). Now we need to bind a click event (click) to each grid ), do I need to execute the following command 100 times?
$ ("Td"). bind ("click", function (){
$ (This). toggleClass ("click ");
});
The answer is no. We only need to bind the event to the table element, because after the Click Event of the td element, the event will "bubble" to the parent element table, this is listened.
Therefore, this event only needs to be bound to the parent element once, instead of 100 times on the child element, which greatly improves the performance. This is called the "delegate processing" of the event, that is, the sub-element "delegate" parent element to process the event.
There are two specific writing methods. The first method is to use the. delegate () method:
$ ("Table"). delegate ("td", "click", function (){
$ (This). toggleClass ("click ");
});
The second method is to use the. live () method:
$ ("Table"). each (function (){
$ ("Td", this). live ("click", function (){
$ (This). toggleClass ("click ");
});
});
These two statements 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. delegate () ratio. live () is a little faster. In addition, these two methods are compared to the traditional one. another benefit of the bind () method is that it is also effective for the dynamically inserted elements ,. bind () is valid only for existing DOM elements and does not apply to dynamically inserted elements.
According to the test, the delegated processing is dozens of times faster than the non-delegated processing. In the case of delegate processing,. delegate () is about 26% faster than. live.
8. Less DOM Structure Changes
(1) modifying the DOM structure is costly. Therefore, do not frequently use methods such as. append (),. insertBefore (), and. insetAfter.
If you want to insert multiple elements, merge them and insert them at a time. According to the test, merging inserts is nearly 10 times faster than not merging inserts.
(2) If you want to perform a large amount of processing on a DOM element, you should first use the. detach () method to extract this element from the DOM. After the processing is complete, re-insert it back into the document. According to the test, the. detach () method is 60% faster than when not in use.
(3) If you want to store data on DOM elements, do not write it as follows:
Var elem = $ ('# elem ');
Elem. data (key, value );
To write it as follows:
Var elem = $ ('# elem ');
$. Data (elem, key, value );
According to the test, the last write method is nearly 10 times faster than the previous one. Because elem. the data () method is defined on the prototype object of the jQuery function, and $. the data () method defines the jQuery function above. It is much faster to call without calling complex jQuery objects. (For details, refer to the following 10th points .)
9. Correct processing cycle
Loop is always a time-consuming operation. If you can use a complex selector to directly select elements, do not use loops to identify elements one by one.
The native javascript loop methods for and while are faster than jQuery's. each () method. The native method should be used first.
10. Generate as few jQuery objects as possible
Every time you use a selector (such as $ ('# id'), a jQuery object is generated. A jQuery object is a very large object with many attributes and methods that occupy a lot of resources. Therefore, generate as few jQuery objects as possible.
For example, many jQuery methods have two versions, one for jQuery objects and the other for jQuery functions. In the following two examples, both extract the text of an element and use the text () method. You can use a version for jQuery objects:
Var $ text = $ ("# text ");
Var $ ts = $ text. text ();
You can also use the version for jQuery functions:
Var $ text = $ ("# text ");
Var $ ts = $. text ($ text );
Because the last version of the jQuery function does not use the jQuery object, it has relatively low overhead and high speed.

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.