JQuery optimization specifications

Source: Internet
Author: User
JQuery is currently one of the most popular Javascript libraries. With the increasing number of jQuery applications, the performance optimization problem cannot be ignored by programmers. We know that the fastest selector in jQuery is the ID selector, because it is directly from the getElementById () method of JavaScript... syntaxHighl

JQuery is currently one of the most popular Javascript libraries. With the increasing number of jQuery applications, the performance optimization problem cannot be ignored by programmers. We know that the fastest selector in jQuery is the ID selector, because it is directly from the getElementById () method of JavaScript.

 

1. always inherit from the ID Selector

For example, there is a piece of HTML code: The following is a reference snippet:

 
 
 

If the following selector is used, the efficiency is inefficient.

The following is a reference clip:
Var traffic_button = $ ("# content. button ");
 

Because the button already has an ID, we can directly use the ID selector. As follows:

The following is a reference clip:
Var traffic_button = $ ("# traffic_button ");
 

Of course, this is only for a single element. If you need to select multiple elements, this will inevitably involve DOM traversal and loops. To improve performance, we recommend that you inherit from the latest ID. As follows:

The following is a reference clip:
Var traffic_lights = $ ("# traffic_light input ");
 

 

2. Use tag (tag Name) before class)
 
In jQuery, the second fastest selector is the tag selector (for example, $ ("head ")). This is because it comes from the native getElementsByTagName () method. Continue to read the HTML code:

The following is a reference clip:



 

For example, if you need to select a red-green single sequence, you can use a tag name to restrict (modify) class, as shown below:

The following is a reference clip:
Var active_light = $ ("input. on ");
 

Of course, you can also combine the nearest ID, as shown below:

The following is a reference clip:
Var active_light = $ ("# traffic_light input. on ");
 

When using tags to modify the class, we need to pay attention to the following points:

(1) do not use tags to modify the ID, as shown below:

The following is a reference clip:
Var content = $ ("div # content ");
 

In this way, the selector first traverses all div elements and then matches the # content.

(2) do not use ID to modify the ID, as shown below:

The following is a reference clip:
Var traffic_light = $ ("# content # traffic_light ");
 

 

3. cache jQuery objects
 
Caching jQuery objects is to tell us the habit of caching jQuery objects into variables. The following is a new piece of code written by jQuery:

The following is a reference clip:
$ ("# Traffic_light input. on"). bind ("click", function (){...});
$ ("# Traffic_light input. on" ).css ("border", "1px dashed yellow ");
$ ("# Traffic_light input. on" background .css ("background-color", "orange ");
$ ("# Traffic_light input. on"). fadeIn ("slow ");
 

But remember not to do this. We should first cache the object into a variable before the operation, as shown below:

The following is a reference clip:
Var $ active_light = $ ("# traffic_light input. on ");
$ Active_light.bind ("click", function (){...});
Using active_light.css ("border", "1px dashed yellow ");
$Active_light.css ("background-color", "orange ");
$ Active_light.fadeIn ("slow ");
 

Remember, never let the same selector appear multiple times in your code:

(1) to distinguish between common JavaScript objects and jQuery objects, you can add the $ symbol before the first letter of the variable.

(2) The above code can be improved using jQuery's chained operation. As follows:

The following is a reference clip:
Var $ active_light = $ ("# traffic_light input. on ");
$ Active_light.bind ("click", function (){...})
. Css ("border", "1px dashed yellow ")
. Css ("background-color", "orange ")
. FadeIn ("slow ");
 

If you want to use jQuery objects in other functions, you must cache them to the global environment. The following code is used:

The following is a reference clip:
// Define an object globally (for example, window object)
Window. $ my = {head: $ ("head"), traffic_light: $ ("# traffic_light"), traffic_button: $ ("# traffic_button")}; function do_something (){
// Now you can reference the stored results and operate on them
Var script = document. createElement ("script ");
$ My. head. append (script );
// When you operate the function internally, you can continue to save the query to the global object. $ my. cool_results = $ ("# some_ul li ");
$ My. other_results = $ ("# some_table td ");
// Use the global function as a common jquery object. parse my.other_results.css ("border-color", "red ");
Export my.traffic_light.css ("border-color", "green ");}
// You can also use it in other functions. 4. restrict direct DOM operations.
 


 
The basic idea here is to create what you really want in the memory and then update the DOM. This is not a jQuery best practice, but it must be used for effective JavaScript operations. Direct DOM operations are slow. For example, if you want to dynamically create a group of list elements, do not do this, as shown below:

The following is a reference clip:
Var top_100_list = [...],
// Assume there are 100 unique strings $ mylist = $ ("# mylist ");
// Select

    Element for (var I = 0, l = top_100_list.length; I "+ Top_100_list [I] +"");}
     

    We should create all the element strings before inserting them into the dom, as shown below:

    The following is a reference clip:
    Var top_100_list = [...], $ mylist = $ ("# mylist"), top_100_li = "";
    // This variable will be used to store our list elements
    For (var I = 0, l = top_100_list.length; I ";}
    Using mylist.html (top_100_li );
     

    Note: I have read this code from a friend before:

    The following is a reference clip:
    For (I = 0; I <1000; I ++ ){
    Var $ myList = $ ('# mylist ');
    $ MyList. append ('this is list item' + I );
    }
     

    You should have seen the problem.

     

    4. Bubble

    Every js event (such as click and mouseover) unless otherwise specified .) Will bubble to the parent node. This is useful when we need to call the same function for multiple elements. Instead of listening to this inefficient multi-element event, you only need to bind it to their parent node once. For example, we need to bind a form with many input boxes to this behavior: when the input box is selected, we add a class to it. The traditional approach is to directly select input and then bind focus, as follows:

    The following is a reference clip:
    $ ("# Entryform input"). bind ("focus", function (){
    $ (This). addClass ("selected") ;}). bind ("blur", function (){
    $ (This). removeClass ("selected ");
    });
     

    Of course, the above Code can help us complete the corresponding tasks, but if you want to find a more efficient method, please use the following code:

    The following is a reference clip:
    $ ("# Entryform"). bind ("focus", function (e ){
    Var $ cell = (e.tar get );
    // E.tar get captures the triggered target Element
    $ Cell. addClass ("selected ");
    }). Bind ("blur", function (e ){
    Var $ cell = (e.tar get); $ cell. removeClass ("selected ");});
     

    You can perform operations on the target element by obtaining the focus and losing the focus in the parent listener. In the code above, the parent element plays the role of a dispatcher, which can bind events based on the target element. If you find that many elements are bound to the same event listener, you must know what is wrong. Similarly, we can use this method to improve the Code during Table operations: the common method:

    The following is a reference clip:
    $ ('# MyTable td'). click (function (){
    Watermark (this).css ('background', 'red ');});
     

    Improvement Method:

    The following is a reference clip:
    $ ('# Mytable'). click (function (e ){
    Var $ clicked = require (e.tar get );
    Export clicked.css ('background', 'red ');});
     

    Suppose there are 100 td instances. When using the common method, you bind 100 events. In the improvement method, you only bind one event to one element. As a result, the efficiency of 100 events is high, and the efficiency of one event is high. I believe you can also identify it on your own.

      

    5. delay until $ (window). load

    JQuery is a very attractive thing for developers to hook anything to $ (document). ready. Although $ (document). rady is indeed 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 probably caused by the $ (document). ready function. You can bind the jQuery function to the $ (window). load event to reduce the cpu usage during page loading. It will. &lt;/P&gt; &lt;p&gt; The following is a reference clip: &lt;br/&gt; $ (window ). load (function () {&amp; nbsp; &lt;br/&gt; &amp; nbsp; // jQuery function initialized only after the page is fully loaded. &lt;br/&gt; &amp; nbsp ;}); &lt;br/&gt; &amp; nbsp; &lt;/p&gt; &lt;p&gt; special effect functions, such as drag-and-drop, visual effects and animations, and pre-loading hidden images are suitable for this technology. &lt;/P&gt; &lt;p&gt; 6. Compress JavaScript &lt;br/&gt; &amp; nbsp; &lt;br/&gt; compress and minimize your JavaScript files. Before compression, make sure that your code is normalized. Otherwise, JavaScript errors may fail. &lt;/P&gt; &lt;p&gt; 7. try to use ID instead of Class &lt;br/&gt; &amp; nbsp; &lt;br/&gt; As mentioned earlier in performance optimization, ID selector is the fastest speed. Therefore, in HTML code, ID can be used instead of class as much as possible. See the following example: &lt;/p&gt; &lt;p&gt; The following is a reference clip: &lt;br/&gt; // create a list &amp; nbsp; var $ myList =$ (&amp; #39; # myList &amp; #39;); &lt;br/&gt; &amp; nbsp; var myListItems = &amp; #39; &lt;ul&gt; &amp; #39; &amp; nbsp; &lt;br/&gt; &amp; nbsp; for (I = 0; I &lt;1000; I ++) {&amp; nbsp; &lt;br/&gt; &amp; nbsp; myListItems + = &amp; #39; &lt;li class = "listItem &amp; #39; + I + &amp; #39;"&gt; This is a list item &lt;/li&gt; &amp; #39 ;; &amp; nbsp; &lt;br/&gt; // class is used here &lt;br/&gt; &amp; nbsp; &amp; nbsp ;}&amp; nbsp; myListItems ==&amp; #39; &lt;/ul&gt; &amp; amp; #39; &amp; nbsp; &lt;br/&gt; &amp;Nbsp;{mylist.html (myListItems); &amp; nbsp; &lt;br/&gt; &amp; nbsp; // select each li &amp; nbsp; for (I = 0; I &lt;1000; I ++) {&amp; nbsp; &lt;br/&gt; &amp; nbsp; var selectedItem =$ (&amp; #39 ;. listItem &amp; #39; + I); &amp; nbsp ;}&lt; br/&gt; &amp; nbsp; &lt;/p&gt; &lt;p&gt; at the end of the Code, it took 5066 milliseconds in total and more than 5 seconds. Next we will make a comparison and use ID instead of class: &lt;/p&gt; &lt;p&gt; The following is a reference segment: &lt;br/&gt; // create a list &amp; nbsp; var $ myList =$ (&amp; #39; # myList &amp; #39;); &amp; nbsp; &lt;br/&gt; &amp; nbsp; var myListItems = &amp; #39; &lt;ul&gt; &amp; #39; &amp; nbsp; &lt;br/&gt; &amp; nbsp; for (I = 0; I &lt;1000; I ++) {&amp; nbsp; &amp; nbsp; myListItems + = &amp; #39; &lt;li id = "listItem &amp; #39; + I + &amp; #39; "&gt; This is a list item &lt;/li&gt; &amp; amp; #39; &lt;br/&gt; &amp; nbsp; // id &amp; nbsp ;}&amp; nbsp; &amp; nbsp; &lt;br/&gt; myListItems + = &amp; #39; &lt;/ul&gt; &amp; #39; &amp; nbsp; &lt;br/&gt; &amp; n Bsp;$myList.html (myListItems); &amp; nbsp; &lt;br/&gt; &amp; nbsp; // select each li &amp; nbsp; for (I = 0; I &lt;1000; I ++) {&amp; nbsp; &lt;br/&gt; &amp; nbsp; var selectedItem =$ (&amp; #39; # listItem &amp; #39; + I); &amp; nbsp; &lt;br/&gt; &amp; nbsp ;}&lt; br/&gt; &amp; nbsp; &lt;/p&gt; &lt;p&gt; in the preceding code, it takes only 61 milliseconds to select each li, which is nearly 100 times faster than the class method. &lt;/P&gt; &lt;p&gt; 8. give the selector a context &lt;br/&gt; &amp; nbsp; &lt;br/&gt; the jQuery selector has such a selector, which can specify the context. &lt;/P&gt; &lt;p&gt; jQuery (expression, context); &amp; nbsp; it can narrow down the search range of selector in the DOM to save time and improve efficiency. &lt;/P&gt; &lt;p&gt; normal mode: &lt;/p&gt; &lt;p&gt; The following is a reference clip: &lt;br/&gt;$ (&amp; amp; #39 ;. myDiv &amp; #39;) &amp; nbsp; &lt;br/&gt; &amp; nbsp; &lt;/p&gt; &lt;p&gt; Improvement Method: &lt;/p&gt; &lt;p&gt; The following is a reference clip: &lt;br/&gt; $ (&amp; amp; #39 ;. myDiv &amp; #39;, $ ("# listItem") &lt;br/&gt; &amp; nbsp; &lt;/p&gt; &lt;p&gt; 9. use with caution. live () method (should be said not to use) &lt;br/&gt; &amp; nbsp; &lt;br/&gt; This is a method added after jQuery1.3.1, the function of this method is to dynamically bind events to the newly added DOM elements. However, for efficiency, this method occupies resources. So try not to use it. For example, there is a piece of code: &lt;/p&gt; &lt;p&gt; The following is a reference snippet: &lt;br/&gt; &lt;script type = "text/javascript"&gt; &lt;br/&gt; &amp; nbsp; $ (function () {&amp; nbsp; $ ("p "). click (function () {&amp; nbsp; &lt;br/&gt; &amp; nbsp; alert ($ (this ). text (); &amp; nbsp;}); &amp; nbsp; &lt;br/&gt; &amp; nbsp; $ ("button "). click (function () {&lt;br/&gt; &amp; nbsp; $ ("&lt;p&gt; this is second p &lt;/p&gt; "). appendTo ("body"); &amp; nbsp ;}); &lt;br/&gt; &amp; nbsp ;}) script &lt;body&gt; &lt;p&gt; this is first p &lt;/p&gt; &lt;Br/&gt; &amp; nbsp; &lt;button&gt; add &lt;/button&gt; &lt;/body&gt; &lt;br/&gt; &amp; nbsp; &lt;/p&gt; &lt;p&gt; after running, you will find that the new p element is not bound to the click event. You can change it. live ("click") to solve this problem, the Code is as follows: &lt;/p&gt; &lt;p&gt; The following is a reference segment: &lt;br/&gt;$ (function () {&amp; nbsp; $ ("p "). live ("click", function () {&lt;br/&gt; &amp; nbsp; // change to live mode &lt;br/&gt; &amp; nbsp; &amp; nbsp; alert ($ (this ). text (); &amp; nbsp ;}); &lt;br/&gt; &amp; nbsp ;$ ("button "). click (function () {$ ("&lt;p&gt; this is second p &lt;/p&gt; "). appendTo ("body") ;}) &lt;br/&gt; &amp; nbsp; &lt;/p&gt; &lt;p&gt; but I do not recommend that you do this, I want to solve this problem in another way. The Code is as follows: &lt;/p&gt; &lt;p&gt; The following is a reference snippet: &lt;br/&gt;$ (function () {&amp; nbsp; $ (" P "). click (function () {&lt;br/&gt; &amp; nbsp; alert ($ (this ). text (); &amp; nbsp ;}); &lt;br/&gt; &amp; nbsp ;$ ("button "). click (function () {&lt;br/&gt; &amp; nbsp; $ ("&lt;p&gt; this is second p &lt;/p&gt; "). click (function () {&lt;br/&gt; &amp; nbsp; // rebind the new element once &amp; nbsp; &lt;br/&gt; &amp; nbsp; &amp; nbsp; alert ($ (this ). text (); &amp; nbsp; &lt;br/&gt; &amp; nbsp ;}). appendT O ("body"); &amp; nbsp ;}) &lt;br/&gt; &amp; nbsp; &lt;/p&gt; &lt;p&gt; although I re-wrote the binding event and added more points to the Code, this method is more efficient than the live () method, this is especially evident in frequent DOM operations. &lt;/P&gt; &lt;p&gt; 10. child selector and descendant selector &lt;/p&gt; &lt;p&gt; descendant selector is often used, for example: $ ("# list &amp; nbsp; p "); the descendant selector obtains all elements inside the element. Sometimes, as long as the child element is obtained, the descendant selector should not be used. The sub-Selector should be used. The Code is as follows: &lt;/p&gt; &lt;p&gt; The following is a reference segment: &lt;br/&gt;$ ("# list&gt; p"); &amp; nbsp; &lt;br/&gt; &amp; nbsp; &lt;/p&gt; &lt;p&gt; 11. use the data () method to store temporary variables &lt;/p&gt; &lt;p&gt; the following code is very simple: &lt;/p&gt; &lt;p&gt; The following is a reference segment: &lt;br/&gt; $ (function () {&amp; nbsp; &lt;br/&gt; &amp; nbsp; var flag = false; &amp; nbsp; &lt;br/&gt; &amp; nbsp; $ ("button "). click (function () {&lt;br/&gt; &amp; nbsp; if (flag) {&amp; nbsp; &lt;br/&gt; &amp; nbsp; &amp; nbsp; $ ("p "). text ("true"); &lt;br/&gt; &amp; nbsp; &amp; nbsp; flag = false; &amp; nbsp; &lt;br/&gt; &amp; nbsp; &amp; nbsp;} else {&amp; nbsp; &lt;br/&gt; &amp; nbsp; &amp; nbsp; $ ("p "). text ("false"); &amp; nbsp; &lt;br/&gt; &amp; nbsp; &amp; nbsp; flag = true; &amp; nbsp; &lt;br/&gt; &amp; nbsp; &amp; nbsp; &amp; nbsp ;}&amp; nbsp; &amp; nbsp ;}); &amp; nbsp; &amp; nbsp ;}) &lt;br/&gt; &amp; nbsp; &lt;/p&gt; &lt;p&gt; after data () is used, the Code is as follows: &lt;/p&gt; &lt;p&gt; The following is a reference clip: &lt;br/&gt; $ (function () {&amp; nbsp; &lt;br/&gt; &amp; nbsp; &amp; nbsp; $ ("button "). click (function () {&lt;br/&gt; &amp; nbsp; if ($ ("p "). data ("flag") {&amp; nbsp; &lt;br/&gt; &amp; nbsp; &amp; nbsp; $ ("p "). text ("true"); &amp; nbsp; &lt;br/&gt; &amp; nbsp; &amp; nbsp; $ ("p "). data ("flag", false); &amp; nbsp; &lt;br/&gt; &amp; nbsp; &amp; nbsp ;}else {&amp; nbsp; &lt;br/&gt; &amp; nbsp; &amp; nbsp; $ ("p "). text ("false"); &amp; nbsp; &lt;br/&gt; &amp; nbsp; &amp; nbsp; $ ("p "). data ("flag", true); &lt;br/&gt; &amp; nbsp; &amp; nbsp ;}&amp; nbsp; &amp; nbsp; &lt;br/&gt; &amp; nbsp; &amp; nbsp ;}); &amp; nbsp; &lt;br/&gt; &amp; nbsp ;}) &lt;br/&gt; &amp; nbsp; &lt;/p&gt;

Related Article

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.