jquery performance Optimization and tips

Source: Internet
Author: User
Tags event listener

1. Use the latest version of the jquery class library

2, use the appropriate selector (below is the basic rules of using selectors, performance down down in descending order)

1) $ ("#id")

Using the ID to locate DOM elements is undoubtedly the best way to lift performance, because the jquery bottom will call the Local method document.getElementById () directly.

If this is not the way to directly find the element you need, consider calling the Find () method.

$ ("#content"). Find ("div")

It is recommended to search from the nearest ID element.

2) $ ("P"), $ ("div"), $ ("input")

jquery will directly call local method Document.getelementbytagname () to locate the DOM element.

3) $ (". Class")

For newer browsers such as IE9, it supports local method Document.getelementbyclassname (). And for the old browser, can only rely on the DOM search method to achieve, there is no doubt that the performance has a greater impact.

4) $ ("[Attribute=value]")

The use of attributes to locate DOM elements is not directly implemented in native JavaScript methods, mostly using DOM search methods to achieve results. Performance is not very ideal. Recommended to avoid in development.

5) $ (": Hidden")

Ditto, not implemented directly in the native JavaScript method. and jquery needs to search every element to locate this selector. Recommended not to use. If you persist in this way, use the ID selector to locate the parent element before you use the selector. Such as:

$ ("#content"). Find (": hidden");

$ ("A.button"). Filter (": Animated");

Note: ① use the ID selector as much as possible.

② Specifies the context for the selector as much as possible.

3. Cache objects

$(function () {//$ ("#traffic_light Input.on"). Bind ("click", Function () {...});//$ ("#traffic_light Input.on"). CSS ("Border", "1px dashed yellow");//$ ("#traffic_light Input.on"). CSS ("Background-color", "orange");//$ ("#traffic_light Input.on"). FadeIn ("slow");//The result is that jquery finds the DOM and creates multiple jquery objects during the creation of each selector ,//the better way to do this is to cache the variables and use the chaining style more succinctly//var $active _light=$ ("#traffic_light input.on");//$active _light.bind ("click", Function () {...})//. css ({//" Border": "1px dashed yellow",//" background-color": "Orange"//                })//. FadeIn ("slow");    }); //If you intend to use jquery objects in other functions, you can cache them in the global environment. window. $my ={head: $ ("Head"), Traffic_light: $ ("#traffic_light"), Traffic_button: $ ("#traffic_button")    }; functiondo_something () {//Now you can reference the stored results and manipulate them        varScript=document.createelement ("Script"); $my. Head.append (script);//When you are working inside a function, 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 normal jquery object$my. Other_results.css ("Border-color", "Red"); $my. TRAFFIC_LIGHT.CSS ("Border-color", "green");//you can also use them in other functions}

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

4. Dom operation at loop time

Using jquery makes it easy to add, delete, or modify DOM nodes, but in some loops, such as for (), while (), or $.each (), note that:

$(function () {//var top_100_list= [];//Suppose this is a 100 unique string//var $myList =$ ("#mylist"); jquery selection to <ul> elements//For (var i= 0;i<top_100_list.length;i++) {//$myList. Append ("<li>" +top_100_list[i]+ "</li>");//        }//a better way to minimize DOM operations is to create the entire element string before inserting the DOM .        vartop_100_list= []; var$myList =$ ("#mylist"); varTop_100_li= "";  for(vari=0;i<top_100_list.length;i++) {Top_100_li+ = "<li>" +top_100_list[i]+ "</li>"; } $myList. html (top_100_li);//Cut Mo//For (Var i=0;i<100;i++) {//var $myList =$ ("#mylist");//$myList. Append ("This is List item" +i);//        }});

5. Use the jquery object in array mode

In terms of performance, it is recommended to use a simple for or while loop instead of $.each ()

    $ (function  () {        var array=new  Array (); //         array=[]; //         Use the Each method        $.each (array, function(i) {            array[i]=i;        }); // Use for instead of the each         () method         for (var i=0;i<array.length; i++) {            array[i]=i;        }    });

In addition, the detection length is a way to check if the jquery object exists.

    $ (function  () {        var $content =$ ("#content");         if ($content) {  // always true//do            something        }        if ($content. Length) {  // owning element returns true//do            something         }    });

6. Event Agent

$(function () {//$ ("#myTable TD"). Click (function () {//$ (this). CSS ("Background", "Red");//        });//above, assume that there are 100 TD elements, in use when the binding of 100 events, which will bring a very negative performance impact//instead of this multi-element event listener, you simply bind one event to their parent node and then get to the current element of the click via Event.target//$ ("#myTable"). Click (function (e) {//var $clicked =$ (e.target);//$clicked. CSS ("Background", "Red");//        });//At the same time, a new way on () is provided in jquery1.7, which encapsulates the entire event listener into a convenient method. $ ("#myTable"). On ("Click", "TD",function(){            $( This). CSS ("Background", "Red");    }); });

7. Convert your code into a jquery plugin

;(function($) {    $.fn.youpluginname=function() {//you        Code goeshere        returnthis;    }) (jQuery);

8. Use join () to stitch the string

You may have used "+" to stitch long strings, but now you can use Join (), which does help optimize performance, especially when long string processing

    $ (function  () {// )    first create an array, then loop, and finally use join () to convert the array to a string        var Array = [];          for (var i = 0; I <= 10000; i++) {            = "<li>" + i + "</li>";        }        $ ("#list"). HTML (Array.join ('));    });

The run effect adds 10,001 li.

9, reasonable use of HTML5 data property

10. Use native JavaScript methods as much as possible

$(function () {//used to determine if a multi box is selected//$cr =$ ("#cr");//$CR. Click (function () {//if ($CR. Is (": Checked")) {//alert ("Thank you for your support!") You can continue to operate! ");//            }//        });//native JavaScript can be used here.        var$CR =$ ("#cr"); varCr= $CR. Get (0); $CR. Click (function(){            if(cr.checked) {alert ("Thank you for your support!" You can continue to operate! ");    }        }); });

Similarly, similar

$ (this). CSS ("Color", "red"); Optimized into this.style.color= "red";
$ ("<p></p>"); Optimized to $ (document.createelement ("P"));

11. Compressing JavaScript

jquery performance Tuning and tricks

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.