Ten Tips for instantly improving jquery performance [Tuts +]

Source: Internet
Author: User
Tags drupal
Document directory
  • 1. Use the latest version.
  • 2. Merge and minimize scripts
  • 3. Replace each with
  • 4. Replace the class selector with ID
  • 5. Specify the front and back text for the selector
  • 6. Create a cache
  • 7. Avoid Dom operations
  • 8. Avoid using Concat () and use join () to process long strings.
  • 9. Return the value of false.
  • 10. Additional tips-cheat sheet and reference documents

This article provides ten steps to immediately improve the performance of your script. Don't worry. This is not an advanced technique. Everyone can use it!
These skills include:

  1. Use the latest version
  2. Merge and minimize scripts
  3. Replacing each with
  4. Replace class selector with ID
  5. Specify the front and back text for the selector
  6. Create Cache
  7. Avoid Dom operations
  8. Avoid using Concat () and use join () to process long strings
  9. Returns false.
  10. Using cheat sheet and reference documents

1. Use the latest version.

Jquery has been in constant development and improvement processes. John and his team are constantly researching new ways to improve program performance.

A few months ago, he also released sizzle, a JS selector library that is said to be able to improve program performance by three times in Firefox.

If you don't want to keep an eye on whether a new version is available and then spend time downloading and uploading it, Google will help you again. Their servers store a large number of Ajax libraries for you to choose from.

<! -- Call an API using a simple script tag -->
<SCRIPT type = "text/JavaScript" src = "http://www.google.com/jsapi"> </SCRIPT>
<SCRIPT type = "text/JavaScript">
/* Load jquery v1.3.2 */
Google. Load ("jquery", "1.3.2", {uncompressed: false });

 

/* Pop up the message after loading */
Function onload (){
Alert ("jquery + Google API! ");
}

Google. setonloadcallback (onload );
</SCRIPT>

Edit:Another simpler and faster method is to directly use the script link. If you want to use a specific version of jquery, you can use the above method. If you want to use the latest version directly, the following code is enough:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>

Stupid jobs: Specific versions can also be loaded as follows:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
2. Merge and minimize scripts

Most browsers cannot process multiple script files at the same time, so the loading time is also extended.

Considering that these scripts are loaded on every page of your website, you should consider placing them in a single file, and then using the compression tool (such as Dean Edwards) to minimize them. Smaller files will undoubtedly increase the loading speed.

JavaScript and CSS compression are designed to reduce the number of bytes transmitted while maintaining the execution performance of the script (you can reduce the size of the original file or use gzip. Most product-level network servers use gzip as part of the HTTP protocol ).

-Imported from Yui compressor, oneJquery official recommendation.

3. Replace each with

Native functions are always faster than helper components.

If you need to traverse objects (such as JSON objects received remotely), You 'd betterRewriteIf your (JSON) object is an array, it is easier to process the array cyclically.

With firebug, we can determine the execution time of each function.

VaR array = new array ();
For (VAR I = 0; I <10000; I ++ ){
Array [I] = 0;
}
Console. Time ('native '); // native for Function
VaR L = array. length;
For (VAR I = 0; I

The above results show that the native code only needs 2 ms, and the use of jquery's each method takes 26 Ms. In addition, this is only the result of testing a function that basically has nothing to do on the local machine. In more complex cases, such as setting CSS attributes or DOM operations, the time difference must be greater.

4. Replace the class selector with ID

Using ID to select an object is much better, because jquery uses the native function getelementbyid () of the browser to get the object, and the query speed is very fast.

Therefore, it is worthwhile to use a more complex selector than to use those convenient CSS selection techniques (jquery also provides us with a complex selector ). You can also manually write your selector (which is simpler than you think), or specify an ID container for the element you want to select.

// Create a list in the following example and fill in the entry content
// Each entry is selected once.

 

// Select using class first
Console. Time ('class ');
VaR list = $ ('# list ');
VaR items ='

    ';

     

    For (I = 0; I <1000; I ++ ){
    Items + ='

  • Item
  •  

    ';
    }

    Items + ='

 

';
List.html (items );

For (I = 0; I <1000; I ++ ){
VaR S = $ ('. item' + I );
}
Console. timeend ('class ');

// Use the ID to select
Console. Time ('id ');
VaR list = $ ('# list ');
VaR items ='

    ';

     

    For (I = 0; I <1000; I ++ ){
    Items + ='

  • Item
  •  

    ';
    }

    Items + ='

 

';
List.html (items );

For (I = 0; I <1000; I ++ ){
VaR S = $ ('# item' + I );
}
Console. timeend ('id ');

The above example demonstrates the significant performance differences between different selection methods. Please see, using class for selection, the time is infinitely increased, or even more than five seconds:

5. Specify the front and back text for the selector

Jquery's reference document says:

The text passed to the original Dom node of jquery () (if nothing is passed, the text is the entire document ).

The purpose is to achieve more accurate query together with the selector.

Therefore, if you must use the class to specify the target, at least specify the context for the selector to avoid jquery's effort to traverse the entire DOM document:

Write it like this:

$('.class').css ('color' '#123456');

It is better to add the front and back texts to the selector (expression: Target selector; Context: front and back texts ):

$(expression, context)

That is to say:

$('.class', '#class-container').css ('color', '#123456');

This is much faster because it does not need to traverse the entire Dom. You only need to find # class-container.

6. Create a cache

Do not make the mistake of constantly selecting the same thing. You should cache the elements you want to process as a variable.

Not to mentionRepeat the same element in a loop! This operation affects the speed!

Items ('items item'detail .css ('color', '#123456 ');
Items ('items item'items .html ('hello ');
Certificate ('background item'0000.css ('background-color', '# ffff ');

 

// Write better
('Items item'0000.css ('color', '0000123456'0000.html('hello'0000.css ('background-color', '# ffff ');

// Even like this
VaR item = $ ('# item ');
Item.css ('color', '#123456 ');
Item.html ('hello ');
Item.css ('background-color', '# ffff ');

// Encounter a loop, which is very bad
Console. Time ('no cache ');
For (VAR I = 0; I <1000; I ++ ){
$ ('# List'). append (I );
}
Console. timeend ('no cache ');

// This is much better
Console. Time ('cache ');
VaR item = $ ('# list ');

For (VAR I = 0; I <1000; I ++ ){
Item. append (I );
}
Console. timeend ('cache ');

As shown in, even for relatively short iterations, the cache effect is very obvious.

7. Avoid Dom operations

The fewer Dom operations, the better, because the insert actions such as prepend (), append (), and after () are time-consuming.

In the preceding example, HTML () is faster:

var list = '';

 

for (var i=0; i<1000; i++) {
list += '

  • '+ I +'
  •  

    ';
    }

    ('{List'{.html (list );

    8. Avoid using Concat () and use join () to process long strings.

    It may sound strange, but doing so can really increase the speed, especially when the connection is particularly long.

    First, create an array and put it into the things you want to concatenate. The join () method is much faster than the Concat () function of the string.

    var array = [];
    for (var i=0; i< =10000; i++) {
    array[i] = '
  • '+ I + '';
    }

     

    ('{List'{.html (array. Join (''));

  • In a recent test initiated by Tom trenka, the following results are obtained:

    "+ = Operator faster-faster than placing string fragments in an array and then joining them". "arrays used as string buffer are more efficient than strings in most browsers. prototype. concat. the apply method is more efficient, except Firefox 2.0.0.14 in windows."

    -Tom trenka

    9. Return the value of false.

    You may have noticed that if the function does not return false after execution, you will be redirected to the top of the page.

    If the page is long, this response is annoying.

    Therefore, unlike this:

    $('#item').click (function () {

     

    // stuff here
    });

    It is better to add one more sentence:

    $('#item').click (function () {
    // stuff here
    return false;
    });
    10. Additional tips-cheat sheet and reference documents

    This suggestion does not directly increase the execution speed of functions. However, if you are willing to spend time on this and study these tips and reference documents, you will save a lot of time in the future.

    Please take a copy at your hand for quick reference.

    From nettut +: 10 Ways to instantly increase your jquery Performance

    Original article from dummies: Ten ways to instantly improve jquery code performance [Tuts +].

    Respect the author and the translator. If you need to reprint the content, you must keep the original link.

    You should also like:
    1. 24 practical suggestions for beginners of JavaScript [Tuts +]
    2. [Translation] basics of JavaScript
    3. [Drupal template creation manual-4]. info file of the topic
    4. 40 practical lightweight JavaScript libraries [sm]
    5. Eight layout schemes for improving design quality [sm]
    6. Use standard CSS to define your table styles
    7. Five Simple tips for adding light effects to your design [sm]
    8. [Drupal template creation manual-2] topic anatomy

    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.