JQuery performance optimization Overview

Source: Internet
Author: User

As a rookie front-end, I still like jquery very much. The initial entry is always the easiest place to start with. I don't know much about jquery's optimization knowledge. I saw an article well written, in fact, there are also related explanations in the "jquery authoritative guide". jquery is well optimized and the speed can be several times faster. It is necessary to learn and use these skills from now on. The following is a record of Ruan Yifeng.

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:

650) this. width = 650; "data-pinit =" registered "src =" http://www.bkjia.com/uploads/allimg/131228/151U460I-0.png "/>

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.

650) this. width = 650; "data-pinit =" registered "src =" http://www.bkjia.com/uploads/allimg/131228/151U45932-1.png "/>

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.

Taking the simplest selector as an example, document. getElementById ("foo") is 10 times faster than $ ("# foo.

Let's take an example and 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 delegated to the Event)

The javascript event model adopts the "bubble" mode. That is to say, the sub-element event is "Bubbling" step by step to become the parent element event.

This can greatly simplify event binding. For example, if there is a table element), there are 100 grid td elements in it), it is now required to bind a click event click on each grid ), do I need to execute the following command 100 times?

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

The answer is no. We only need to bind this event to the table element, because after the Click Event of the td element, this 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" the parent element to process the event.

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

The better way is to bind the event to the document Object.

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

If you want to cancel event binding, use the off () method.

$ (Document). off ("click", "td ");

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 also has an effect on 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, so 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 to 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 a DOM element, do not write it as follows:

Var elem = $ ('# elem ');Elem. data (key, value );

To write

Var elem = $ ('# elem ');$. Data (elem [0], 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. See the following 10th points .)

4) When html code is inserted, the native innterHTML () method of the browser is faster than the html () method of the jQuery object.

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 isJQuery objectThe version used. The other isJQuery FunctionsThe version used. 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.

11. Select the shortest method of the scope chain

Strictly speaking, this principle applies to all Javascript programming, not just jQuery.

We know that Javascript variables use chained scopes. When reading a variable, search for the variable in the current scope. If the variable cannot be found, search for the variable in the previous scope. This design makes it much faster to read local variables than to read global variables.

See the following two codes. The first code reads global variables:

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

The second Code reads local variables:

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

When the second Code reads variable a, it does not need to go to the upper-layer scope, so it is five or six times faster than the first code.

Similarly, the closure mode is faster than the prototype mode when calling object methods.

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 ;}};};

The same is the get_name () method, and the closure mode is faster.

12. Use Pub/Sub mode to manage events

When an event occurs, if you want to execute multiple operations consecutively, it is best not to write it as follows:

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

Instead, use the event trigger mode:

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 );}

2013.7.12 update, Source

13. postpone some functions to $ (window). load for execution.

Although $ (document ). ready is really useful. It can be executed before other elements are downloaded during page rendering. if you find that your page is always in the loading status, it is likely to be $ (document ). caused by the ready function.

You can bind the jquery function to $ (window ). load event method to reduce the cpu usage during page loading. it will be executed after all html (including <iframe>) are downloaded.

14. Merge and minimize scripts

All scripts are loaded in a queue. Therefore, we should minimize the number of JS files and use compression tools to compress JS files.

15. When DOM insertion is required, all elements are encapsulated into one element.

Direct DOM operations are slow. Change the HTML structure as little as possible.

Var menu = '<ul id = "menu">'; for (var I = 1; I <100; I ++) {menu + = '<li>' + I + '</li>';} menu + = '</ul>'; $ ('# head '). prepend (menu); // do not do this: $ ('# head '). prepend ('<ul id = "menu"> </ul>'); for (var I = 1; I <100; I ++) {$ ('# menu '). append ('<li>' + I + '</li> ');}
16. Use jQuery's internal function data () to store the status

Do not forget to use the. data () function to store information:

$ ('# Head '). data ('name', 'value'); // call $ ('# head') in your application '). data ('name ');
All rights reserved. The source must be specified for reprinting.

Original: front-end blog link: http://caibaojian.com/front/447

0


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.