10 tips for improving jquery performance

Source: Internet
Author: User

Transferred from: http://www.jb51.net/article/43198.htm

1. Use the latest version of jquery

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 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 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.

Consider the following example, binding a function that handles a click event for a element:

$ (' 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"). BIND ("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.

There are two kinds of specific wording. 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 types of writing are basically equivalent. The only difference is that. Delegate () is triggered when an event bubbles to the specified parent element, and. Live () is triggered when the event bubbles to the root element of the document, so. Delegate () is slightly faster than. Live (). In addition, there is a benefit to the two methods compared to the traditional. Bind () method, which is also valid for dynamically inserted elements. Bind () is valid only for DOM elements that already exist and is not valid for dynamically inserted elements.

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

8. Change the DOM structure less

(1) It is expensive to change the DOM structure, 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 it, and then re-insert it 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,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.) )

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.

10 tips for improving jquery performance

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.