How to Write high-quality jQuery code (jquery performance problems)

Source: Internet
Author: User

1. Correctly reference jQuery

1. Try to introduce jQuery before the body ends, rather than in the head.
2. Use a third-party CDN to introduce jQuery. Note that when a problem occurs with a third-party CDN, you must introduce a local jQuery file. (For websites that have already used cdn, you can ignore this because the user's bandwidth has been upgraded. It is not necessarily stable to put other users on the machine)
3. if you introduce a script file before </body>, you do not need to write document. ready because DOM has been loaded when JavaScript code is executed.

<body> <script src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="jquery1.8.min.js">\x3C/script>')</script></body>

2. optimized the jQuery selector.

Efficient and correct use of the jQuery selector is the basis for skillful use of jQuery. It takes some time to master the jQuery selector. When we start to learn about jQuery, we should pay attention to the usage of the selector.

<Div id = "nav" class = "nav"> <a class = "home" href = "http://www.jb51.net"> script house </a> <a class = "articles" href = "http://www.jb51.net/list/list_172_1.htm"> jQuery tutorials </a> </div>

If we select the element whose class is home, we can use the following code:

$('.home'); //1$('#nav a.home'); //2$('#nav').find('a.home'); //3

1. method 1 will make jQuery look for a element whose class is home in the entire DOM, and the performance can be imagined.
2. method 2 adds a context for the element to be searched. Here, the context is changed to the child element whose id is nav, which greatly improves the search performance.
3. Method 3 uses the find method, which is faster, so method 3 is the best.

For the performance priority of the jQuery selector, the ID selector is faster than the element selector and the element selector is faster than the class selector. Because the ID selector and element selector are native JavaScript operations, but the class selector is not, you can see the difference between find context and find () children by the way.

3. cache jQuery objects

Caching jQuery objects can reduce unnecessary DOM searches. For more information, see cache jQuery objects to improve performance.

4. Use event delegation correctly
Event delegation can make the event execution better. It is also required to bind events to dynamically added elements, in the new version of jQuery, we recommend that you use on to bind one or more event handler functions to the element.

<Table id = "t"> <tr> <td> I am a cell </td> </tr> </table>

For example, if we want to bind a click event to the above cell, a friend who doesn't pay attention to it may write it as below:

$('#t').find('td').on('click', function () { $(this).css({ 'color': 'red', 'background': 'yellow' });});

In this way, events will be bound to each td. In the test of binding a click event to 100 cells, the performance of the two is seven times different. The good practice should be as follows:

$('#t').on('click', 'td', function () { $(this).css({ 'color': 'red', 'background': 'yellow' });});

5. Simplified jQuery code
For example, in the above Code, we have properly merged jQuery code, similar to the. attr () method. We have not written the following method:

$('#t').on('click', 'td', function () { $(this).css('color', 'red').css('background', 'yellow');});

6. Reduce DOM operations
When jQuery is used at the beginning, DOM operations may be performed frequently, which is quite performance-consuming. For example, if we want to dynamically output a table in the body, some friends will write:

var $t = $('body');$t.append('<table>');$t.append('<tr><td>1</td></tr>');$t.append('</table>');

Good practice:

$('body').append('<table><tr><td>1</td></tr></table>');

In this way, after splicing the table string and then adding it to the body, you only need to perform DOM operations once. Some friends in the group used to have a problem in output under IE because of this. For details about String concatenation, refer to the fastest way to create a string.

7. Do not use jQuery

Native functions are always the fastest, which is hard to understand. In code writing, we should not forget native JS.

Let's sum up these items first. It is not difficult to understand each piece of suggestion, but it takes a lot of time to make a conclusion. For example, if you want to get a new array from the array according to the conditions in the reduce code segment, you can use $. grep () method. If you have to use jQuery, you are welcome to share it with you in your message!

The following is a supplement from other netizens:

Note: add the var keyword when defining the jQuery variable.
This is not just jQuery. It should be noted in all javascript development processes. Please do not define it as follows:

$ Loading = $ ('# loading'); // This is a global definition. If you do not know where the same variable name is referenced, it will be depressing.

Use a var to define variables
If you use multiple variables, define them as follows:

Copy codeThe Code is as follows:
Var page = 0,
$ Loading = $ ('# loading '),
$ Body = $ ('body ');

Do not add a var keyword to every variable unless you have serious obsessive-compulsive disorder.
Define jQuery Variables
When declaring or defining a variable, remember to add a $ symbol before the variable if you are defining the jQuery variable, as shown below:

Var $ loading = $ ('# loading ');

The benefit is that you can effectively prompt yourself or other users who read your code. This is a jQuery variable.

Make sure to remember the cache for DOM operations)

In jQuery code development, we often need to operate the DOM. DOM operations are a process that consumes a lot of resources, and many people usually like to use jQuery like this:

Copy codeThe Code is as follows:
Certificate ('{loading'{.html ('complete ');
$ ('# Loading'). fadeOut ();

The Code does not have any problems, and you can run the results normally, but note that each time you define and call $ ('# loading'), a new variable is actually created, if you need to reuse the variable, remember to define it into a variable. This effectively caches the variable content as follows:

Copy codeThe Code is as follows:
Var $ loading = $ ('# loading ');
Uploloading.html ('complete'); $ loading. fadeOut ();

This will provide better performance.

Use chained operations

In the example above, we can write more concisely:

Copy codeThe Code is as follows:
Var $ loading = $ ('# loading ');
Uploloading.html ('complete'). fadeOut ();

Simplified jQuery code

Try to integrate some code together. Do not encode it like this:

Copy codeThe Code is as follows:
//!! Negative $ button. click (function (){
Define target.css ('width', '123 ');
Using target.css ('border', '1px solid #202020 ');
Define target.css ('color', '# fff ');
});

It should be written as follows:

Copy codeThe Code is as follows:
$ Button. click (function (){
Export target.css ({'width': '000000', 'border': '1px solid # 000000', 'color': '# fff '});
});

Avoid using global Selector

Do not write as follows: $ ('. something> *');
It is better to write: $ ('. something'). children ();

Do not overlay multiple IDs

Do not write as follows: $ ('# something # children ');
This is enough: $ ('# children ');

Multi-purpose logic judgment | or & to speed up

Do not write as follows:

Copy codeThe Code is as follows:
If (! $ Something ){
$ Something = $ ('# something ');
}

The writing performance is better:

$ Something = $ something | $ ('# something ');
 
 
Try to use less code

Write it like this: if (string. length> 0 ){..}

It is better to write as follows: if (string. length ){..}

Use the. on method whenever possible
If you use a newer version of The jQuery class library, use. on. Any other method is implemented using. on.

Use the latest jQuery version whenever possible
The latest version of jQuery has better performance, but the latest version may not support ie6/7/8, so you need to choose your own based on the actual situation.

Try to use native Javascript
If you can use native Javascript to implement the functions provided by jQuery, we recommend that you use native javascript.

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.