10 methods for jQuery code performance optimization, jquery Performance Optimization

Source: Internet
Author: User

10 methods for jQuery code performance optimization, jquery Performance Optimization

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

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

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('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 would a normal jQuery result $my.other_results.css('border-color', 'red'); $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="/">  

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> elementfor (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 itemsfor (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 100 unique strings $mylist = $('#mylist'), // jQuery selects our <ul> element top_100_ul = '<ul id="#mylist">'; // This will store our entire unordered listfor (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, 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 stated, 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 a large form that contains many inputs, we want to bind a class name when the input is selected. 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.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 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 jQuery does not find any matching elements, it still takes time to search. If your site has a global JavaScript, you may 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 is that your template can fully control the execution of JavaScript internal scripts at any time or place to 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 out of the page, or you need them to be optimized later for the purpose of visualization. You should immediately place the original 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 into the hypocritical event $ (document). ready. After all, we can see this in most examples. Although $ (document). ready is very useful, it occurs 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 caused by $ (document). ready. You can help set jQuery functions to $ (window ). load event to reduce the CPU usage during downloading. It calls all objects after all HTML (including iframe content) are downloaded.

$(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. It is a trend to make JavaScript Functions and variables readable. This is essential for developers, but it does not matter to common users. 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 to compress excess 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, 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 check jQuery documents and manuals.

The above is all about this article. For more information about jQuery syntax, see jQuery 1.10.3 online manual.

Related Article

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.