Optimize jquery to increase page loading speed _jquery

Source: Internet
Author: User
Tags event listener tag name cpu usage jquery library

Always inherit from ID selector
Use the tag before class
Caching a JQuery object
Mastering the powerful chain operation
Using subqueries
Restricting direct DOM operations
Bubble
Eliminate invalid queries
Defer to $ (window). Load
Compress JS
Full control of the jquery library

1. Always inherit from ID selector

The fastest selector in jquery is the ID selector. Because it comes directly from the JavaScript getElementById () method.

Copy Code code as follows:

<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"/>
</ul>
<input class= "button" id= "Traffic_button" type= "submit" value= "Go"/>
</form>
</div>

Selecting buttons like this is inefficient:

var Traffic_button = $ (' #content. Button ');
Selecting a button directly with an ID is more efficient:

var Traffic_button = $ (' #traffic_button ');

Select multiple elements

The reference to multiple element selection is actually talking about DOM traversal and looping, which are slow things. To improve performance, it is best to inherit from the nearest ID.

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

2. Use tag before class

The second fastest selector is the tag Selector ($ (' head ')). Similarly, because it comes from the native getElementsByTagName () method.

Copy Code code as follows:

<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"/>
</ul>
<input class= "button" id= "Traffic_button" type= "submit" value= "Go"/>
</form>
</div>

Always use a tag name to limit (Modify) class (and do not forget the nearest ID):

var active_light = $ (' #traffic_light input.on ');

Note: class is the slowest selector in jquery. In IE, it traverses all DOM nodes regardless of where it is used.

Do not use tag name to decorate IDs. The following example iterates through all the DIV elements to find which node ID is ' content ':

var content = $ (' div#content '); Using an ID to decorate the ID is also superfluous:

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

3. Cache the jquery objects

Get into the habit of caching a jquery object into a variable.

Never do this:

Copy Code code as follows:

$ (' #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 ');

It's a good idea to cache objects into a variable before you manipulate it:
Copy Code code as follows:

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

To keep in mind that our local variables are encapsulated in jquery, we usually prefix it with a $. Remember, never let the same selector appear more than once in your code.

Cache jquery results, standby
If you intend to use the jquery results object in other parts of your program, or if your function executes multiple times, then cache them in a global variable.

By defining a global container to store the jquery results, we can reference them in other functions:

Copy Code code as follows:

Defines an object (for example: Window object) in the global scope
window. $my =
{
Initialize all queries that may be used more than once
Head: $ (' head '),
Traffic_light: $ (' #traffic_light '),
Traffic_button: $ (' #traffic_button ')
};
function do_something ()
{
Now you can refer to the stored results and manipulate them
var script = document.createelement (' script ');
$my. Head.append (script);
When you operate inside a function, you can continue to store the query in the global object.
$my. Cool_results = $ (' #some_ul Li ');
$my. Other_results = $ (' #some_table TD ');
Use global functions as a common jquery object.
$my. Other_results.css (' Border-color ', ' red ');
$my. Traffic_light.css (' Border-color ', ' green ');
}

4. Master the powerful chain-type operation

The example above can also be written like this:

Copy Code code 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 can be written less code, so that our JS lighter volume.

5. Use a subquery

JQuery allows us to use additional selector actions on a wrapped object. Because we have saved a parent object in a variable, this greatly increases the operation of its child elements:

Copy Code code as follows:

<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"/>
</ul>
<input class= "button" id= "Traffic_button" type= "submit" value= "Go"/>
</form>
</div>

For example, we can use the subquery method to grab the light or not light, and cache it for subsequent operation.
Copy Code code as follows:

var $traffic _light = $ (' #traffic_light '),
$active _light = $traffic _light.find (' Input.on '),
$inactive _lights = $traffic _light.find (' Input.off ');

Tip: You can declare multiple local variables one at a time by using a comma-delimited method-Save the number of bytes

6. Restrictions on direct DOM operations

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 has to be a valid JavaScript operation. Direct DOM operations are slow.

For example, if you want to create a set of list elements dynamically, don't do this:

Copy Code code as follows:

var top_100_list = [...],//Suppose this is a 100 unique string
$mylist = $ (' #mylist '); JQuery selection to <ul> elements
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:
Copy Code code 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] + ' </li> ';
}
$mylist. HTML (TOP_100_LI);

We will be quicker to wrap multiple elements into a single parent node before inserting:
Copy Code code as follows:

var top_100_list = [...],
$mylist = $ (' #mylist '),
Top_100_ul = ' <ul id= ' #mylist ' > ';
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> '; Turn off unordered lists
$mylist. ReplaceWith (Top_100_ul);

If you've done a few of these or are worried about performance problems, then:

Try the jquery Clone () method, which creates a copy of the node tree that allows you to do DOM operations in an "offline" manner, and then put it back in the node tree when you're done.

Use DOM documentfragments. As the jquery author puts it, its performance is significantly better than direct DOM operations.

7. Bubbling

Unless in exceptional circumstances, otherwise each JS event (for example: click, mouseover, etc.) Will bubble to the parent node. This can be useful when we need to call the same function for multiple elements.

Instead of this inefficient, multiple-element event listener, you only have to bind to their parent node once, and you can calculate which node triggers the event.

For example, we want to bind a form with many input boxes to do this: Add a class to it when the input box is selected

Binding events like this is inefficient:

Copy Code code as follows:

$ (' #entryform input '). Bind (' Focus ', function () {
$ (this). AddClass (' selected ');
}. Bind (' blur ', function () {
$ (this). Removeclass (' selected ');
});

We need to listen to the events in the parent to get focus and lose focus:
Copy Code code as follows:

$ (' #entryform '). Bind (' Focus ', function (e) {
var cell = $ (e.target); E.target grabs the node that triggered the event.
Cell.addclass (' selected ');
}. Bind (' blur ', function (e) {
var cell = $ (e.target);
Cell.removeclass (' selected ');
});

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 bound to the same event listener, then you must have done something wrong.

8. Eliminate invalid Query

Although jquery can gracefully handle a situation where there are no matching elements, it still takes time to find it. If you have only one global JS in the entire station, it is very likely that all of the jquery functions will be stuffed into $ (document) Ready (function () {//All your Proud code}).

Only functions that are used in the page are run. The most effective approach is to use inline initialization functions so that your template can control exactly when and where to execute JS.

For example, your "article" page template, you might refer to the following code at the end of the body:

<script type= "text/javascript>
Mylib.article.init ();
</script>
</body>

If your page template contains some variable modules that may not appear on the page, or you need them to load quickly for visual presentation, you can follow the initialization function immediately after the module.

<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"/>
</ul>
<script type= "text/javascript>
Mylib.traffic_light.init ();
</script>

Your Global JS library might be like this:

var mylib =
{
Article_page:
{
Init:function ()
{
Article's unique jquery function.
}
},
Traffic_light:
{
Init:function ()
{
Traffic Light's unique jquery function.
}
}
}

9. Defer to $ (window). Load

jquery has a tempting thing for developers to hang anything up to $ (document). Ready under a fake event. In most cases, you will find this.

Although the $ (document). Rady is really useful, it can be performed when the page is rendered and the other elements are not finished downloading. If you find that your page has been in the loading state, it is likely to be $ (document). The Ready function causes.

You can reduce the CPU usage when the page is loaded by binding the jquery function to the $ (window). Load event method. It will be executed after all HTML (including <iframe>) is downloaded.

$ (window). Load (function () {
The jquery function that is initialized when the page is fully loaded.
});

Redundant features such as drag-and-drop, visual effects and animations, preload hidden images, and so on. are all suitable for this kind of technology occasion.

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.