10 ways to optimize jquery code _jquery

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

1, always use #id to find element.

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

<div id= "Content" >

 <form method= "POST" action= "/" >

   
 

One way to choose the bad performance of a button:

var Traffic_button = $ (' #content. Button ');

Instead, select the button directly:

var Traffic_button = $ (' #traffic_button ');

Select multiple elements

When we talk about selecting multiple elements, what we really need to know is that DOM traversal and looping are the reasons for poor performance. To minimize performance loss, always use the nearest parent ID to find it.

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

2. Use tags in front of classes

The second fastest selector in jquery is the tag selector (the ' head '). This is because it maps directly to the JavaScript getElementsByTagName () method.

<div id= "Content" >

 <form method= "POST" action= "/" >

   
 

Always precede a class with a tag name (remember to pass from one ID)

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

Note: In jquery the class selector is the slowest selector; in IE it loops through the DOM. Try to avoid using it if possible. Do not add tags in front of the ID. For example, it will go through all the <div> elements to find the <div> with ID content, which causes it to be slow.

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

In the same way, it is redundant to pass multiple IDs.

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

3. Caching jquery objects

Get into the habit of keeping jquery objects on a variable (like the example above). 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 then continue with 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: Using the $ prefix indicates that our local variable is a jquery package set. Remember not to have more than one jquery repeat selection in your program. Extra TIP: Delay storing jquery object results.

If you want to use the jquery results object (Result object (s)) elsewhere in your program, or if your function executes multiple times, cache it in a globally scoped object. By defining a global container to hold the jquery result object, you can reference it in other functions.

Define an object in the global scope (i.e. Windows object)

window. $my ={

 //Initialize all the queries and you W Ant to use the than once head: $ (' head

 '),

 traffic_light: $ (' #traffic_light '),

 Traffic_button: $ (' #traffic _button ')};

function do_something () {

 //now can reference the stored results and manipulate them

 var script = Document.cre Ateelement (' 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 your would a normal jQuery result

 $my. Other_results.css (' Border-color ', ' red ');

 $my. Traffic_light.css (' Border-color ', ' green ');



4, better use of the chain

The preceding example can also be written like this:

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 lighter.

5. Use subqueries

jquery allows us to attach additional selectors on a set of packages. Because we have saved the parent object in the local variable, this will reduce the performance overhead on the selector later.

<div id= "Content" >

 <form method= "POST" action= "/" >

   
 

For example, we can use subqueries 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 one at a time, which saves some bytes.

6. Restrict direct to DOM operations

The basic approach to DOM operations is to create a DOM structure in memory and then update the DOM structure. This is not the best way to jquery, but it's efficient for JavaScript. Direct manipulation of DOM structure performance is low. For example, if you need to create a column of elements dynamically, do not:

var top_100_list = [...],//Assume this has a unique strings 

$mylist = $ (' #mylist ');//JQuery selects our <UL&G T 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 unique strings 

$mylist = $ (' #mylist '),//JQuery selects our <UL&G T Element 

Top_100_li = "";  This would store our list

of items 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);

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

var top_100_list = [...],//Assume this has unique strings 

$mylist = $ (' #mylist '),//JQuery selects our <UL&G T Element 

Top_100_ul = ' <ul id= ' #mylist > '//This'll store our entire unordered list

for (Var i=0, l=top_1 00_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 have done the above or are somewhat puzzled by the performance, you can refer to the following:

* Try the Clone () method provided by jquery. The Clone () method creates a copy of the number of nodes, which you can then manipulate in this copy.

* Use Dom documentfragments. As the creator of JQuery points out, better than directly manipulating DOM performance. Create the structure you need first (as we did with a string above), and then use the Insert or Replace methods of jquery.

7, event delegate (also name: Bubbling event)

Unless otherwise noted, each JavaScript event (such as Click, MouseOver, and so on) bubbles onto its parent element on the DOM structure tree. This is useful if we want many elements (nodes) to invoke the same function. Instead, you can bind to their parent only once, and you can figure out which node triggers the event, rather than binding an event listener to this inefficient way on many nodes. For example, if we want to develop a large form that contains many input, we want to bind a class name when input is selected. A help like this is inefficient:

$ (' #myList li '). bind (' click ', Function () {

 $ (this). addclass (' clicked ');/do Stuff

});

Instead, we should listen for the Click event at the parent level.

$ (' #myList). bind (' click ', Function (e) {

 var target = e.target,//E.target grabs the node that triggered the event.
   
     $target = $ (target); Wraps the node in a JQuery object

 if (target.nodename = = ' LI ') {

  $target. addclass (' clicked ');  Do Stuff

 }

});


   

The parent node acts as a transmitter and can do some work on the target element that triggers the event. If you find yourself setting an event listener to a number of element, you are not right to do so.

8, eliminate the query waste

While jquery does a good job of not finding any matching elements, it still takes time to find it. If your site has a global JavaScript, you might put each jquery function in $ (document). Ready (function () {//All my Glorious Code}). Don't do that. Just put some function on the page for use. The most effective way to do this is to have your template complete control of initializing the function at any time or place to execute JavaScript inline script. For example, in your "article" page template, you might 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 a variety of modules that are likely to be on the page or not on the page, or if you need them to be ready for visualization, you should place the first function immediately after the 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 should look 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 to get jquery developers to hook everything up to $ (document). Ready this hypocritical event. After all, you can see this in most cases. Although $ (document). Ready is useful, it occurs when the page is rendered, although other objects are still in the download. If you find that your page pauses in the download, it could be $ (document). Ready caused. You can use the jquery functions to help set the $ (window). Load event to reduce CPU usage at download time when all HTML (including IFRAME content) is downloaded before all objects are invoked.

$ (window). Load (function () {

 //JQuery functions to initialize after the page has loaded.

});

Redundant features such as drag-and-drop, visual effects and animation, pre-read pictures, etc., are better to use this method.

10, Compression JS

It has nothing to do with jquery, but here's a mention. Making JavaScript functions and variables readable is a trend that is essential for developers, but does not matter to ordinary users. No excuse, it is time to put JS compression into our work flow. Annotate your code and find a compression tool to compress before you drop it into the production environment. Use Yuicompressor to compress the extra wasted bytes in your code. According to our experience, it is safe to compress JavaScript as small as possible without consuming more CPU. Tip: To maximize compression in yuicompressor, you should define variables like this (for example, Var my_long_variable_name;)

The best way to learn and use jquery most effectively is to look up jquery's documentation and manuals.

The above is the entire contents of this article, to learn more jquery syntax, you can see: "JQuery 1.10.3 Online Handbook", but also hope that we support the cloud-Habitat community.

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.