Ten tips for improving jQuery performance

  • 2020-03-29 23:44:03
  • OfStack

1. Use the latest version of jQuery

JQuery updates quickly, and you should always use the latest version. Because the new version will improve performance, there are many new features.

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

$('. Elem ')

$('. Elem ', the context)

The context. Find ('. Elem ')

We tested jQuery with versions 1.4.2, 1.4.4, and 1.6.2 to see how many times the browser could execute in a second. The results are as follows:
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201311/0_1330944342Rbh4.png ">

As you can see, version 1.6.2 runs far more than the two older versions. The first statement, in particular, improves performance several times.

Tests for other statements, such as.attr(" value ") and.val(), are also better than the old version.

2. Use the right selector

In jQuery, you can use multiple selectors to select the same page element. The performance of each selector is different and you should be aware of the performance differences.

(1) the fastest selector: id selector and element label selector

For example, the following statements perform best:

$(' # id ')

$(' form ')

$(" input ")

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

(2) slower selector: class selector

The performance of $('.classname ') depends on the browser.

Firefox, Safari, Chrome, Opera, all have the native method getElementByClassName(), so it's not slow. However, ie5-ie8 does not deploy this method, so the selector will be quite slow in IE.

(3) the slowest selector: pseudo-class selector and attribute selector

So let's look at an example. To find all the hidden elements in the web page, you need to use the pseudo-class selector:

$(' hidden ')

An example of a property selector is:

Value] [attribute = $(' ')

These two statements are the slowest because the browser has no native methods for them. However, new versions of some browsers add the querySelector() and querySelectorAll() methods, so the performance of such selectors can be greatly improved.

Finally, a performance comparison of the different selectors.


< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201311/0_1330944365soi4.png ">

As you can see, the ID selector is way ahead, then the label selector, then the Class selector, and then all the other selectors are very slow.

3. Understand the relationship between child and parent elements

The following six selectors select child elements from parent elements. 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 go through the sentence.

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

Given a DOM object, then select a child element from it. JQuery automatically converts this statement to $.parent. Find (' child'), which results in a performance penalty. It's 5-10% slower than the fastest form.

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

This is the fastest statement. The.find() method calls the browser's native methods (getElementById, getElementByName, getElementByTagName, and so on), so it's faster.

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

Inside jQuery, this statement USES $.sibling() and javascript's nextSibling() method to walk through the nodes one at a time. It's about 50% slower than the fastest form.

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

JQuery USES the Sizzle engine internally to handle various selectors. The Sizzle engine selects from right to left, so this statement selects the.child and then filters out the parent element #parent one by one, causing it to be about 70% slower than the fastest form.

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

This statement is the same as the previous one. However, while the previous one selects only direct child elements, this one can select multiple child elements, so it is slower, about 77% slower than the fastest form.

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

JQuery internally converts this statement to $(' #parent').find('.child'), which is 23% slower than the fastest form.

So the best choice is $parent.find('.child'). Furthermore, since $parent is often generated in the previous operation, jQuery caches it, which further speeds up the execution.

For specific examples and comparison results, see here.

4. Don't overuse jQuery

No matter how fast jQuery is, it can't compete with the native javascript methods. So where native methods are available, try to avoid jQuery.

See the following example of binding a function to handle the click event for the a element:

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

Alert ($(this). Attr (" id "));

});

This code means that when you click on the a element, the id attribute of that element pops up. To get this property, you must call jQuery twice in a row, the first time $(this) and the second time attr(' id').

In fact, this treatment is totally unnecessary. More correctly, use the javascript native method to call this.id:

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

Alert (this. Id);

});

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

5. Cache

Selecting a web element is an expensive step. Therefore, use the selector as few times as possible, and cache the selected results as much as possible for later reuse.

For example, this is a bad way to write it:

JQuery (' # top '). Find (' p.c lassA ');

JQuery (' # top '). Find (' p.c lassB ');

A better way to write it is:

Var cached = jQuery (' # top ');

Cached. Find (' p.c lassA ');

Cached. Find (' p.c lassB ');

In tests, caching is 2-3 times faster than not caching.

6. Use chain notation

One of the great things about jQuery is that it allows you to write in a chain.

$(' div '). The find (' h3 '). Eq. (2) the HTML (' Hello ');

With chaining, jQuery automatically caches the results of each step, so it is faster than non-chaining. According to tests, chained writing is about 25 percent faster than (without caching) non-chained writing.

7. Event Delegation

The javascript event model USES the "bubble" mode, that is, the events of the child elements will bubble up to become the events of the parent element.

Taking advantage of this, you can greatly simplify the binding of events. For example, if you have a table (table element) with 100 cells (td element), now you need to bind a click event to each cell. Do you need to execute the following command 100 times?

$(" td "). The bind (" click ", function () {

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

});

The answer is no, we just need to bind the event to the table element, because the event "bubbles" to the parent element table after the td element clicks.

Therefore, this event only needs to be bound to the parent element once instead of the child element 100 times, which greatly improves performance. This is called the "delegate handling" of the event, where the child element delegates the parent element to handle the event.

There are two ways to write it. The first is the dot delegate() method:

$(" table "). The delegate (" td ", "click", function () {

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

});

The second is to use the. Live () method:

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

$(" td ", this) live (" click ", function () {

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

These two ways are basically equivalent. The only difference is that.delegate() is triggered when the event bubbles to the specified parent, and.live() is triggered when the event bubbles to the document's root, so.delegate() is slightly faster than.live(). In addition, both of these methods have an advantage over the traditional.bind() method, which also works for dynamically inserted elements,.bind() works only for existing DOM elements, not for dynamically inserted elements.

According to tests, delegation processing is dozens of times faster than non-delegation processing. In the delegate case,.delegate() is about 26% faster than.live().

8. Make few changes to the DOM structure

(1) DOM structure changes are expensive, so don't use methods like.append(),.insertbefore (), and.insetafter () too often.

If you want to insert multiple elements, merge them and then insert them all at once. According to tests, merge inserts are nearly 10 times faster than no merge inserts.

(2) if you're going to do a lot of work with a DOM element, you should use the. Detach () method to take the element out of the DOM and insert it back into the document when you're done. According to testing, using the. Detach () method is 60% faster than not using it.

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

Var elem = $(' # elem ');

Elem. Data (key, value);

Instead, write:

Var elem = $(' # elem ');

$. Data (elem, key, value);

According to tests, the latter method is nearly 10 times faster than the former. Since the elem.data() method is defined above the prototype object of the jQuery function, the $.data() method is defined above the jQuery function and is not called from a complex jQuery object, so it is much faster. (see point 10 below here.)

9. Handle the loop correctly

Looping is always a time-consuming operation. If you can use a complex selector to select elements directly, don't use looping to identify elements one by one.

Javascript native loop methods, for and while, are faster than jQuery's. Each () method and should be used in preference to native methods.

10. Generate as few jQuery objects as possible

Each time you use a selector (such as $(' #id')), a jQuery object is generated. JQuery object is a very large object, with many properties and methods, will take up 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 one for jQuery functions. The following two examples both fetch the text of an element using the text() method. You can either use the version for jQuery objects:

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

Var $ts = $text. The text ();

You can also use the version for jQuery functions:

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

Var $ts = $. Text ($text);

Since the latter version for jQuery functions does not operate on jQuery objects, it is relatively inexpensive and fast.


Related articles: