JQuery Performance Optimization

Source: Internet
Author: User

Previously, we reduced the number of bytes, the number of requests, and the loading order to make the page Load faster. Today, we are increasingly paying attention to another part that affects website performance-CPU utilization. Using jQuery and other JavaScript frameworks makes node selection and DOM operations easier. improper use may affect the response speed of the entire webpage, the following lists 11 more efficient jQuery libraries:

1. Always use # id to find the element.

The fastest selector in jQuery is the ID selector ($ ('# someid'). This is because it is directly mapped to the getElementById () method of JavaScript.
Select a single element

<Div id = "content">
<Form method = "post" action = "/">
<H2> Traffic Light <Ul id = "traffic_light">
<Li> <input type = "radio" name = "light" value = "red"/> Red </li>
<Li> <input type = "radio" name = "light" value = "yellow"/> Yellow </li>
<Li> <input type = "radio" name = "light" value = "green"/> Green </li>
</Ul>
<Input id = "traffic_button" type = "submit" value = "Go"/>
</Form>
</Div>

One way to choose a button with poor performance:
Var traffic_button = $ ('# content. click ');

Instead, select the button directly:
Var traffic_button = $ ('# traffic_button ');

Select multiple elements

When we discuss how to select multiple elements, what we really need to know is that DOM traversal and loops are the cause of low performance. To minimize performance loss, always use the nearest parent ID to search.

Var traffic_lights = $ ('# traffic_light input ');

2. Use Tags before Classes

In jQuery, the second fast selector is the Tag selector ($ ('head'). This is because it is directly mapped to the getElementsByTagName () method of JavaScript.

<Div id = "content">
<Form method = "post" action = "/">
<H2> Traffic Light <Ul id = "traffic_light">
<Li> <input type = "radio" name = "light" value = "red"/> Red </li>
<Li> <input type = "radio" name = "light" value = "yellow"/> Yellow </li>
<Li> <input type = "radio" name = "light" value = "green"/> Green </li>
</Ul>
<Input id = "traffic_button" type = "submit" value = "Go"/>
</Form>
</Div>

Always add a tag name in front of a Class (remember to pass it down from an ID)

Var active_light = $ ('# traffic_light input. on'); note: In jQuery, the Class selector is the slowest one; in IE, It loops through the entire DOM. Avoid using it if possible. Do not add Tags before the ID. For example, it loops through all the <div> elements to find the <div> with the ID as content, resulting in a very slow process.

Var content = $ ('div # content'); in the same way, it is redundant to pass multiple IDs.

Var traffic_light = $ ('# content # traffic_light ');

3. cache jQuery objects

Develop the habit of saving jQuery objects to a variable (like in the above example. For example, do not do this:

$ ('# Traffic_light input. on). bind ('click', function (){...});
$ ('# Traffic_light input.on).css ('border', '3px dashed yellow ');
$ ('# Traffic_light input.on).css ('background-color', 'Orange ');
$ ('# Traffic_light input. on). fadeIn ('low ');

Instead, save the jQuery variable to a local variable and continue your operation.

Var $ active_light = $ ('# traffic_light input. on ');
$ Active_light.bind ('click', function (){...});
Using active_light.css ('border', '3px dashed yellow ');
Using active_light.css ('background-color', 'Orange ');
$ Active_light.fadeIn ('low ');

Tip: use $ prefix to indicate that our local variable is a jQuery package set. Remember, do not show more than one repeated jQuery selection operation in your program. Tip: delay in storing jQuery object results.

If you want to use the jQuery result object (s) elsewhere in your program, or your function needs to be executed multiple times, it must be cached in a global object. By defining a global container to save the jQuery result object, you can reference it in other functions.

// Define an object in the global scope (I. e. the window object)
Window. $ my = {
// Initialize all the queries you want to use more than once
Head: $ ('head '),
Traffic_light: $ ('# traffic_light '),
Traffic_button: $ ('# traffic_button ')};
Function do_something (){
// Now you can reference the stored results and manipulate them
Var script = document. createElement ('script ');
$ My. head. append (script );
// When working inside functions, continue to save jQuery results
// To your global container.
$ My. cool_results = $ ('# some_ul li ');
$ My. other_results = $ ('# some_table td ');
// Use the global functions as you wowould a normal jQuery result
Export my.other_results.css ('border-color', 'red ');
Using my.traffic_light.css ('border-color', 'green ');
}

4. Better utilization chain

The preceding example can also be written as follows:

Var $ active_light = $ ('# traffic_light input. on ');
$ Active_light.bind ('click', function (){...})
. Css ('border', '3px dashed yellow ')
. Css ('background-color', 'Orange ')
. FadeIn ('slow ');

This allows us to write less code and make JavaScript more lightweight.

5. Use subquery

JQuery allows us to append other selectors to a package set. Because we have saved the parent object in the local variable, this will reduce the performance overhead on the selector in the future.

<Div id = "content">
<Form method = "post" action = "/">
<H2> Traffic Light <Ul id = "traffic_light">
<Li> <input type = "radio" name = "light" value = "red"/> Red </li>
<Li> <input type = "radio" name = "light" value = "yellow"/> Yellow </li>
<Li> <input type = "radio" name = "light" value = "green"/> Green </li>
</Ul>
<Input id = "traffic_button" type = "submit" value = "Go"/>
</Form>
</Div>

For example, we can use the subquery to cache active and inactive lights for subsequent operations.

Var $ traffic_light = $ ('# traffic_light '),
$ Active_light = $ traffic_light.find ('input. on '),
$ Inactive_lights = $ traffic_light.find ('input. off ');

Tip: You can use commas to separate multiple local variables at a time to save some bytes.

6. restrict direct DOM operations

The basic method of DOM operations is to create a DOM structure in the memory and then update the DOM structure. This is not jQuery's best practice, but it is efficient for JavaScript. The performance of operating the DOM structure directly is low. For example, if you want to dynamically create a column of elements, do not do this:

Var top_100_list = [...], // assume this has 100 unique strings
$ Mylist = $ ('# mylist'); // jQuery selects our <ul> element
For (var I = 0, l = top_100_list.length; I <l; I ++ ){
$ Mylist. append ('<li>' + top_100_list + '</li> ');
}

Instead, we want to create a set of elements in a string before inserting the DOM structure.
Code

Var top_100_list = [...], // assume this has 100 unique strings
$ Mylist = $ ('# mylist'), // jQuery selects our <ul> element
Top_100_li = ""; // This will store our list items
For (var I = 0, l = top_100_list.length; I <l; I ++ ){
Top_100_li + = '<li>' + top_100_list + '</li> ';
}
Using mylist.html (top_100_li );

Faster, we should always include many elements in a parent node before inserting the DOM structure.

Var top_100_list = [...], // assume this has 100 unique strings
$ Mylist = $ ('# mylist'), // jQuery selects our <ul> element
Top_100_ul = '<ul id = "# mylist">'; // This will store our entire unordered list
For (var I = 0, l = top_100_list.length; I <l; I ++ ){
Top_100_ul + = '<li>' + top_100_list + '</li> ';
}
Top_100_ul + = '</ul>'; // Close our unordered list
$ Mylist. replaceWith (top_100_ul );

If you are still confused about the performance based on the above, you can refer to the following content:

 

 

Try the Clone () method provided by jQuery. The Clone () method creates a copy of the number of nodes, and then you can operate on the copy.

Use DOM DocumentFragments. as the creator of jQuery points out, better performance than direct DOM operations. first, create the structure you need (just as we did with a string above), and then use jQuery's insert or replace methods.


7. Event delegation (also known as bubble events)

Unless otherwise specified, every JavaScript event (such as click and mouseover) will bubble to its parent element on the DOM structure tree. It is very useful if we want many elements (nodes) to call the same function. Instead, you can bind the parent nodes only once and calculate which node triggers the event, instead of binding an event listener to many nodes, this method is inefficient. For example, if we want to develop

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.