Ten jQuery optimization notes for beginners, and jquery for beginners

Source: Internet
Author: User

Ten jQuery optimization notes for beginners, and jquery for beginners

JQuery Optimization

1. Introduction
JQuery is becoming the preferred JavaScript library for Web developers. As a Web developer, in addition to understanding the application skills of languages and frameworks, how to improve the performance of the language itself is also a question that developers should think about. Taking jQuery as an example, this article provides you with 10 tips to effectively improve jQuery's performance.

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.

Derived from YUI compressor, a compression script tool officially recommended by jQuery: JavaScript and CSS compression are designed to maintain the script execution performance while, reduce the number of bytes transmitted by data (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 ).

3. Replace each with

Native functions are always faster than helper components. If you need to traverse an object (such as a JSON Object received remotely), You 'd better rewrite your (JSON) object into an array, so 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 <l; I ++) {array [I] = I;} console. timeEnd ('native '); console. time ('jquery '); // jquery's each method $. each (array, function (I) {array [I] = I;}); console. timeEnd ('jquery ');

The results show that the native code only takes 2 milliseconds, and the use of jQuery's each method takes 26 milliseconds. 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. // use class to select console. time ('class'); var list = $ ('# list'); var items =' <ul> '; for (I = 0; I <1000; I ++) {items + = '<li> item </li>';} items + = '</ul>'; list.html (items ); for (I = 0; I <1000; I ++) {var s = $ ('. item '+ I);} console. timeEnd ('class'); // then use the ID to select the console. time ('id'); var list = $ ('# list'); var items =' <ul> '; for (I = 0; I <1000; I ++) {items + = '<li id = "item' + I + '"> item </li>';} items + = '</ul> '; 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 the class for selection, the time is infinitely increased, or even more than five seconds

5. Specify the front and back text for the selector

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 and write it like this:

Certificate ('.class'0000.css ('color' #123456 ');

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. Do not repeatedly select the same element in a loop! This operation affects the speed!

Items ('items item'0000.css ('color', '#123456'); items ('items item'hangzhou.html ('hello'); items ('items item'hangzhou.css ('background-color', '# ffff '); // write a better example ('items item'0000.css ('color', '0000123456'0000.html('hello'0000.css ('background-color', '# ffff'); // even var item =$ (' # item '); item.css ('color', '#123456'); item.html ('hello'); item.css ('background-color', '# ffff'); // encountered a loop, this is a very poor console. time ('no cache'); for (var I = 0; I <1000; I ++) {$ ('# list '). append (I);} console. timeEnd ('no cache'); // The console is much better. time ('cache'); var item = $ ('# list'); for (var I = 0; I <1000; I ++) {item. append (I);} console. timeEnd ('cache ');

 

Even for a relatively short iteration, 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 += '<li>' + i + '</li>'; } $('#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] = '<li>' + i + '</li>'; } $('#list').html(array.join ('')); 

 

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

 

One sentence:

$('#item').click(function() { // stuff here return false; ); 

10. Research

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.

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.