How to write high quality jquery code (using jquery performance issues) _jquery

Source: Internet
Author: User

1. Correct reference to jquery

1. Try to introduce jquery before the body ends, not in head.
2. Using a Third-party CDN to introduce jquery, and note that the local jquery file is introduced when a problem arises with a third party CDN. (For the site has been used CDN can be ignored, now the user bandwidth has been upgraded, this can be ignored, put others machine is not necessarily stable)
3. If you introduce a script file before </body>, you don't need to write document.ready, because the DOM is already loaded when you execute the JS code.

<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. Optimize the jquery selector

Efficient and correct use of the jquery selector is the basis for a skilled use of jquery, while mastering the jquery selector requires a certain amount of time to accumulate, when we begin to learn jquery should be aware of the use of the selector.

<div id= "nav" class= "nav" >
 <a class= "Home" href= "http://www.jb51.net" > Cloud-dwelling community </a>
 <a class= "articles" href= "http://www.jb51.net/list/list_172_1.htm" >jquery tutorials </a>
</div>

If we select a element with Class A home, you can use the bottom code:

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

1. Method 1 enables jquery to find a element of class home in the entire DOM, which can be imagined.
2. Method 2 Adds a context to the element to find, where it becomes a child element that looks for the id nav, and the lookup performance is greatly improved.
3. Method 3 uses the Find method, which is faster, so the best method is three.

With regard to 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 the element selector are native JavaScript operations, and the class selector is not, you can look in the Find context difference, see () Children difference.

3. Caching jquery objects

Caching jquery objects can reduce unnecessary DOM lookups, and for this you can refer to caching jquery objects to improve performance.

4. Proper use of event delegation
event delegates allow events to be better executed, and binding events on dynamically added elements also need to be delegated to implement, and in the new version of jquery We recommend that you use on to bind the elements to one or more event-handling functions.

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

For example, we want to bind a click event on the top cell, and a friend who doesn't notice may write the following:

$ (' #t '). Find (' TD '). In (' Click ', Function () {
 $ (this). css ({' Color ': ' Red ', ' background ': ' Yellow '});
});

This will tie up events for each TD, and in the test for 100 cell-bound click events, the performance is 7 times times the difference, and a good practice should be the following:

$ (' #t '). On (' Click ', ' TD ', function () {
 $ (this). css ({' Color ': ' Red ', ' background ': ' Yellow '});
});

5. Streamlining jquery Code
as in the above code we did a proper merge of the jquery code, similar to the. attr () method, etc., we did not write the following way:

$ (' #t '). On (' Click ', ' TD ', function () {
 $ (this). CSS (' Color ', ' red '). CSS (' background ', ' yellow ');
});

6. Reduce DOM Operations
the DOM can be manipulated frequently when you start using jquery, which is quite performance-intensive. If we want to dynamically output a table in the body, some friends will write this:

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

This will be added to the body after the table string is spliced, and the DOM can be manipulated only once. The group has a friend in the past because of this led to the output in IE under the problem, and the concatenation of strings can refer to the fastest way to create a string.

7. Do not use jquery

The original function is always the fastest, this is not difficult to understand, in code writing we should not forget the native JS.

Let's sum up these few, each piece of advice is not difficult to understand, but it still takes a lot of time to summarize the overall statement. For example, if you need to get a new array from an array based on conditions, you can use the $.grep () method if you have your own when you use jquery, and you are welcome to share it with us in your message!

The following are additional users:

Note When defining jquery variables, add the var keyword
This is not just jquery, all JavaScript development process, should be noted, please do not define as follows:

$loading = $ (' #loading '); This is a global definition, do not know where the bad luck reference the same variable name, will be depressed to death

Please use a var to define the variable
If you use multiple variables, define the following:

Copy Code code as follows:

var page = 0,
$loading = $ (' #loading '),
$body = $ (' body ');

Do not add a var keyword to each variable unless you have severe obsessive-compulsive disorder.
Defining jquery Variables
When declaring or defining variables, keep in mind that if you are defining a jquery variable, add a $ symbol to the variable before, as follows:

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

The good thing about this is that you can effectively prompt yourself or other users who read your code, which is a jquery variable.

Dom operations be sure to remember caching (cache)

In jquery code development, we often need to manipulate dom,dom operations is a very resource consuming process, and often many people like to use jquery:

Copy Code code as follows:

$ (' #loading '). html (' finished ');
$ (' #loading '). fadeout ();

The code doesn't have any problems, you can also run the results normally, but notice that each time you define and call $ (' #loading '), you actually create a new variable, and if you need to reuse it, remember to define it in a variable so that you can effectively cache the variable contents as follows:

Copy Code code as follows:

var $loading = $ (' #loading ');
$loading. HTML (' finished '); $loading. fadeout ();

This will improve performance.

Using chained operations

The above example, we can write a little more concise:

Copy Code code as follows:

var $loading = $ (' #loading ');
$loading. HTML (' finished '). fadeout ();

Streamline jquery Code

Try to integrate some of the code together, do not encode this:

Copy Code code as follows:

!! Villain $button.click (function () {
$target. css (' width ', ' 50% ');
$target. CSS (' border ', ' 1px solid #202020 ');
$target. CSS (' color ', ' #fff ');
});

It should be written like this:

Copy Code code as follows:

$button. Click (function () {
$target. css ({' width ': ' 50% ', ' border ': ' 1px solid #202020 ', ' Color ': ' #fff '});
});

Avoid using a global type selector

Do not write in the following way: $ ('. something > * ');
This is better to write: $ ('. something '). Children ();

Do not overlay multiple IDs

Do not write as follows: $ (' #something #children ');
That's enough: $ (' #children ');

Multi-use logical judgment | | or && to speed up

Please do not write as follows:

Copy Code code as follows:

if (! $something) {
$something = $ (' #something ');
}

This writing performance is better:

$something = $something | | $ (' #something ');


try to use less code

Write this: if (String.Length > 0) {.}

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

Try to use the. On method
use. On if you use the new version of the JQuery class library, and any other method is ultimately used. On.

Try to use the latest version of jquery
The latest version of jquery has better performance, but the latest version may not support IE6/7/8, so you need to choose for yourself.

Try to use native JavaScript
If using native JavaScript can also implement the functionality that jquery provides, it is recommended to use native JavaScript for implementation.

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.