JQuery Performance Optimization

Source: Internet
Author: User
Tags event listener tag name

1, always start inheriting from ID selector
The fastest selector in jquery is the ID selector because it comes directly from the JavaScript getElementById () method. For example, there is an HTML code: <div id= "Content" > <form method= "Post" action= "#" > 2, use tag (sign) before class

The second fastest selector in jQuery is the tag selector (for example, $ ("Head")). When tired with the ID selector, it comes from the native getElementsByTagName () method. Just keep looking at the HTML code: <div id= "Content" > <form method= "Post" action= "#" > When using tag to decorate class, we need to pay attention to the following points: (1) do not use tag to decorate the ID, as follows: var content = $ ("div#content"); As a result, the selector iterates through all DIV elements and then matches #content. (as if JQuery had changed the selector core from 1.3.1, there was no problem.) Temporarily unable to verify. ) (2) Do not use the ID to decorate the ID as follows: var traffic_light = $ ("#content #traffic_light"); Note: If you use the attribute selector, also use tag to decorate as follows: $ (' p[row= ' c3221 "]). HTML (); instead of: $ (' [row= ' c3221"]). HTML ();
Special Note: The Tag.class mode is better than the. Class mode under IE. But under Firefox, it's lower than the direct. Class mode. Both are similar in the Google browser. I have 300 elements on my page, and their performance gaps are within 50 milliseconds.

3. Cache JQuery Objects

Caching jquery objects is about telling us to get into the habit of caching jquery objects into variables. Here's a jQuery new handwritten piece of code: $ ("#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"); But remember not to do so. We should first cache the object into a variable and then manipulate it as follows: var $active _light = $ ("#traffic_light Input.on"); $active _light.bind ("click", Function () {...}); $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. Note: (1) in order to distinguish between ordinary JavaScript objects and JQuery objects, you can precede the first letter of the variable with the $ symbol. (2) The above code can be improved using JQuery's chained operation. as follows: 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 intend to use JQuery objects in other functions, you must cache them in the global environment. The following code shows://Defines an object (for example: Window object) in the Global scope window. $my = {head: $ ("Head"), Traffic_light: $ ("#traffic_light"), Traffic_butto N: $ ("#traffic_button")}; function do_something () {///Now you can reference stored results and manipulate them var script = document.createelement ("script"); $my. head.append (script); /When you are working inside the 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 it in other functions
4, limit the direct DOM operation
The basic idea here is to build what you really want in memory and then update the DOM. This is not a jQuery best practice, but it must be done in a valid JavaScript operation. The direct DOM operation is slow. For example, if you want to dynamically create a list of elements, do not do so as follows: var top_100_list = [...],//Suppose here are 100 unique strings $mylist = $ ("#mylist"); JQuery selection to <ul> element for (Var i=0, l=top_100_list.length; i<l; i++) {$mylist. Append ("<li>" + top_100_list[ I] + "</li>"); We should create the entire set of element strings before inserting them into the DOM, as follows: 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<l; i++) {top_100_li + = "<li>" + top_100_list[i] + "&L T;/li> "; } $mylist. html (TOP_100_LI); Note: Remember that you've seen a friend write code like this before: for (i = 0; i < i++) {var $myList = $ (' #myList '); $myList. Append (' The IS List item ' + i); Oh, you should have seen the problem. Since the #mylist cycle has been acquired 1000 times!!!
5, bubbling
Except in special cases, each JS event (for example: click, mouseover, etc.) Will bubble to the parent node. This is useful when we need to invoke the same function for multiple elements. Instead of this inefficient multi-element event listener, you only have to bind to their parent node once. For example, we would like to bind a form with a lot of input boxes: When the input box is selected, adding a class for it is traditionally done by selecting input directly, then binding focus, and so on, as follows: $ ("#entryform input"). Bind (" Focus ", function () {$ (this). AddClass (" selected ");}). Bind ("Blur", function () {$ (this). Removeclass ("selected");});
Of course the above code can help us do the task, but if you want to find a more efficient way, please use the following code: $ ("#entryform"). Bind ("Focus", function (e) {var $cell = $ (e.target); E.target snaps to the triggering target element $cell. addclass ("selected"); }). bind ("Blur", function (e) {var $cell = $ (e.target); $cell. Removeclass ("selected");}); The target element is manipulated by listening for the event that gets focus and loses focus at the parent level. 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 you have a lot of elements that are bound to the same event listener, now you know what's wrong. Similarly, in Table operations, we can also use this approach to improve the code: the Normal Way: $ (' #myTable TD '). Click (function () {$ (this). CSS (' background ', ' red ');}); Improved mode: $ (' #myTable '). Click (function (e) {var $clicked = $ (e.target); $clicked. css (' background ', ' red ');}); Assuming there are 100 TD, you are bound to 100 events when using the normal way. In the improved mode, you only bind 1 events for one element, and as for 100 events, the efficiency of the 1 events is high, and I believe you can distinguish them by yourself.
6, deferred to $ (window). Load
JQuery is a tempting thing for developers to hook anything up to $ (document). Although $ (document). Ready is really useful, it can be executed when the page is rendered and other elements are not downloaded. If you find that your page has been loaded in the state, it is likely that $ (document). The Ready function is causing the. You can reduce the CPU usage on page load by binding the JQuery function to the $ (window) Load event method. It will be executed after all the HTML (including <iframe>) has been downloaded. $ (window). Load (function () {//the JQuery function initialized after the page is fully loaded.});
Features such as drag-and-drop, visual effects and animations, pre-loading hidden images, and more are all suitable for this technology.
7, compressing JavaScript
Compress and minimize your JavaScript files. Online compression Address: http://dean.edwards.name/packer/compression before, please ensure that your code is normative, otherwise it may fail, resulting in Js error.
8, try to use the ID instead of Class.
Previous performance optimizations have said that the speed of the ID selector is the fastest. So in the HTML code, you can use the ID as far as possible to use the ID instead of class. Look at one of the following examples://Create a list var $myList = $ (' #myList '); var mylistitems = ' <ul> '; for (i = 0; i < i++) {mylistitems + = ' <li class= ' listItem ' + i + ' ">this are a list item</li> '; The class} Mylistitems + = ' </ul> ' is used here; $myList. HTML (mylistitems); Select each Li for (i = 0; i < i++) {var SelectedItem = $ ('. ListItem ' + i)} at the end of the code, the process of selecting each Li takes a total of 5066 milliseconds and more than 5 Seconds. Then we make a comparison with the ID instead of class://Create a list var $myList = $ (' #myList '); var mylistitems = ' <ul> '; for (i = 0; i < i++) {mylistitems + = ' <li id= ' listItem ' + i + ' ">this are a list item</li> '; The id} mylistitems + = ' </ul> ' is used here; $myList. HTML (mylistitems); Select each Li for (i = 0; i < i++) {
var SelectedItem = $ (' #listItem ' + i); In the previous code, selecting each Li took a total of 61 milliseconds, nearly 100 times times faster than class. 9, give the selector a context
There is one such selector in the JQuery selector, which can specify the context. JQuery (expression, context); With it, you can reduce the range of selectors in the DOM to save time and improve efficiency. Normal way: $ ('. Mydiv ') Improved way: $ ('. Mydiv ', $ ("#listItem"))
10, use the. Live () method (should say try not to use)
This is an addition to the jQuery1.3.1 version, and the function of this method is to dynamically bind events to the new DOM elements. But for efficiency, this method is more resource-intensive. So please try not to use it. For example, there is a piece of code: <script type= "Text/javascript" > $ (Function () {$ ("P"). Click (function () {alert (this). text ());}); $ ( "button"). Click (function () {$ ("<p>this is second p</p>"). AppendTo ("Body");}); }) </script> <body> <p>this is first p</p> <button>add</button> </body> running, You will find the new P element and do not use the Bind click event. You can change the. Live ("click") method to resolve this problem, the code is as follows: $ (function () {$ ("P"). Live ("Click", Function () {///change to Live Mode alert ($ (this). text ());
}); $ ("button"). Click (function () {$ ("<p>this is second p</p>"). AppendTo ("Body");}) But I do not recommend that you do this, I would like to solve this problem in another way, the code is as follows: $ (function () {$ ("P"). Click (function () {alert (this). text ());}); $ ("button"). Click (function () {$ ("<p>this is second p</p>"). Click (function () {//) to rebind the new element once alert (this). text ());}). AppendTo ("body"); }); }) Although I have re-written the binding event again, the code is a bit more efficient, but this is significantly more effective than the live () approach, especially in frequent DOM operations.
11, child selector and descendant selector
Descendant selectors are often used, for example: $ ("#list P"); The descendant selector gets all the elements inside the element. Sometimes, however, the descendant selectors should not be used if the child element is actually acquired. A sub-selector should be used, with the following code: $ ("#list > P"); 12, use the data () method to store temporary variables
Here is a very simple code, $ (function () {var flag = false; $ ("button"). Click (function () {if (flag) {$ ("P"). Text ("true"); flag=false;} else{$ ("P"). Text ("false"); flag=true;}); })
After using the data () mode, the code is as follows: $ (function () {$ ("button"). Click (function () {if ("P"). Data ("flag")) {$ ("P"). Text ("true"); $ ("" P "). Data ("flag", false); }else{$ ("P"). Text ("false"); $ ("P"). Data ("flag", True);}); })
This concludes the JQuery Performance optimization Guide

JQuery Performance Optimization

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.