Jquery Performance Optimization

Source: Internet
Author: User
Tags 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="/">


<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 .button');

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="/">


<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 start with ID
Add tags. 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('slow');

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(){...});$active_light.css('border', '3px dashed yellow');$active_light.css('background-color', 'orange');$active_light.fadeIn('slow');

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 </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 <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 [I] + '</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,
It is better than operating the DOM directly. First create the structure you need (just as we did with a string above), and then use jquery insert or
Replace methods.

7. Event delegation (also known as bubble events)

Unless otherwise specified, each JavaScript event (such as click, Mouseover
Etc.) in the DOM structure tree, it will bubble to its parent element. It is very useful if we want many elements (nodes) to call the same function. Instead

You can only bind the parent nodes once, and calculate which node triggers the event, instead of binding an event listener to many nodes. For example, if we want to develop
A large form that contains many inputs. When input is selected, we want to bind a class name. Such a helper 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 listener to multiple elements, this is incorrect.

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
Every jquery function can be placed 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 &
GT; if your page template contains multiple 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 original response letter after these modules
Number.

<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 to $ (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
Compress 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.

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.