About jquery Performance Optimization

Source: Internet
Author: User
Tags jquery library website performance

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. Use
Jquery and other JavaScript frameworks make node selection and Dom operations more and more easy. improper use may affect the response speed of the entire web page.
Efficient use of the jquery Library:

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 </H2>
<Ul id = "traffic_light">
<Li> <input type = "radio" class = "on" name = "light" value = "red"/> Red </LI>
<Li> <input type = "radio" class = "off" name = "light" value = "yellow"/> yellow </LI>
<Li> <input type = "radio" class = "off" name = "light" value = "green"/> green </LI>
</Ul>
<Input class = "button" 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 fastest 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 </H2>
<Ul id = "traffic_light">
<Li> <input type = "radio" class = "on" name = "light" value = "red"/> Red </LI>
<Li> <input type = "radio" class = "off" name = "light" value = "yellow"/> yellow </LI>
<Li> <input type = "radio" class = "off" name = "light" value = "green"/> green </LI>
</Ul>
<Input class = "button" 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 selector; 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, transmitting data from multiple IDS is redundant.

 
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, you should notProgramMore than one repeated jquery selection operation appears.
Tip: delay in storing jquery object results.

If you want to use the jquery result object (Result
Object (s), or your function needs to be executed multiple times and 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 lessCodeTo 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 </H2>
<Ul id = "traffic_light">
<Li> <input type = "radio" class = "on" name = "light" value = "red"/> Red </LI>
<Li> <input type = "radio" class = "off" name = "light" value = "yellow"/> yellow </LI>
<Li> <input type = "radio" class = "off" name = "light" value = "green"/> green </LI>
</Ul>
<Input class = "button" 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 [I] + '</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 [I] + '</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
    element
    top_100_ul = '
      '; // This will store our entire unordered list

      for (VAR I = 0, L = top_100_list.length; I {
      top_100_ul + = '
    • ' + top_100_list [I] + '
    • ';
      }< BR minmax_bound = "true"> top_100_ul + = '
    '; // close our unordered list

    $ mylist. replacewith (top_100_ul);

if you follow the above steps and are still confused about performance, 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. create the structure you need first (just as we did with a string above),
then use jquery's insert or replace methods.

7. event Delegate (also known as bubble event)

unless otherwise stated, every JavaScript event (such as click, 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 a
large form that contains many inputs, we want to bind a class name when the input is selected. Such a decision is inefficient:

$ ('# Mylist Li). BIND ('click', function (){
$ (This). addclass ('clicked ');
// Do stuff
});

Instead, we should listen for click events at the parent level.

 
$ ('# Mylist). BIND ('click', function (e ){
VaR target = e.tar get, // e.tar get grabs the node that triggered the event.
$ Target = $ (target); // wraps the node in a jquery object
If (target. nodename = 'lil '){
$ Target. addclass ('clicked ');
// Do stuff
}
});

The parent node is responsible for sending the report, and can do some work on the target element that triggers the event. If you find yourself setting an event
This method is incorrect if listener helps you set multiple elements.

8. Eliminate query waste

Although
Although jquery does not find any matching elements, it still takes time to search. If your site has a global JavaScript, you can
Can put every jquery function in $ (document). Ready (function () {// all my glorious code
. Do not do this. Only function suitable for use on some pages. The most effective way to do this is that your template can fully control the execution of JavaScript internal scripts anytime or anywhere.
Initialize the function. For example, in your "article" Page Template, you may include the following code before the body tag is closed.

 
<SCRIPT type = "text/JavaScript>
Mylib. Article. INIT ();
</SCRIPT>
</Body>

If your page template contains a variety of modules that may be on or not on the page, or you need them to be optimized later for visualization, you should immediately place the initial functions after these modules.

<Ul id = "traffic_light">
<Li> <input type = "radio" class = "on" name = "light" value = "red"/> Red </LI>
<Li> <input type = "radio" class = "off" name = "light" value = "yellow"/> yellow </LI>
<Li> <input type = "radio" class = "off" name = "light" value = "green"/> green </LI>
</Ul>
<SCRIPT type = "text/JavaScript>
Mylib. traffic_light.init ();
</SCRIPT>

Your global JavaScript library looks like this:

VaR mylib =
{
Article_page:
{
Init: function ()
{
// Article Page specific jquery functions.
}
},
Traffic_light:
{
Init: function ()
{
// Traffic light specific jquery functions.
}
}
}

 

9. Follow $ (Windows). Load

There is a temptation for jquery developers to hook everything up
$ (Document). ready in this hypocritical event. After all, we can see this in most examples. Although $ (document). Ready
It is very useful when the page is rendered, although other objects are still being downloaded. If you find that your page is paused during download, it may be $ (document). Ready
. You can
Functions helps to set the $ (window). Load event to reduce the CPU usage during downloading. It is only after all HTML (including IFRAME content) are downloaded.
To call all objects.

 
$ (Window). Load (function (){
// Jquery functions to initialize after the page has loaded.
});

This method provides additional functions, such as drag and drop, visualization effects and animations, and pre-reading images.

 

10. compressing JS

It has nothing to do with jquery, but it should be mentioned here. Making JavaScript Functions and variables readable is a trend, which is essential for developers, but for common users
It does not matter. There is no excuse to include JavaScript compression in our workflow. Comment out your code and find a compression tool before it is put into the production environment for compression. Use
Yuicompressor compresses unnecessary wasted bytes in your code. Based on our experience, it can safely compress JavaScript as little as possible without occupying the CPU. TIPS:
To maximize compression in yuicompressor, define the variable (for example, VAR my_long_variable_name ;)

 

11. Learn about jquery api library documentation

The best way to learn and use jquery most effectively is to check jquery documents and use them as manuals.

Online show recommendationArticle: Http://www.wangshow.com/blog/article_show/38/273736/jQuery-performance-rules

 

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.