22 points about jquery performance optimization recommendations _jquery

Source: Internet
Author: User

First, keep in mind that JQuery is JavaScript. This means that we should adopt the same coding conventions, style guides and best practices.

First of all, if you're a beginner of JavaScript, I recommend you read "JavaScript Best practices for beginners", a high-quality JavaScript tutorial that you should read before you touch jQuery.

When you are ready to use jQuery, I strongly recommend that you follow these guidelines:

1. Cache variables

DOM traversal is expensive, so try to reuse the element cache.

Copy Code code as follows:

Bad
h=$ (' #element '). Height ();
$ (' #element '). CSS (' height ', h-20);

Copy Code code as follows:

Suggestions
$element =$ (' #element ');
H= $element. Height ();
$element. css (' height ', h-20);

2. Avoid global variables

JQuery, like JavaScript, generally, it's best to make sure that your variables are within the scope of the function.

Copy Code code as follows:

Bad
$element =$ (' #element ');
H= $element. Height ();
$element. css (' height ', h-20);

Copy Code code as follows:

Suggestions
var $element =$ (' #element ');
var h= $element. Height ();
$element. css (' height ', h-20);

3. Use of the Hungarian nomenclature

Add the $ prefix before the variable to easily identify the JQuery object.

Copy Code code as follows:

Bad
var first=$ (' #first ');
var second=$ (' #second ');
var value= $first. Val ();

Copy Code code as follows:

Recommendation-add $ prefix to JQuery object
var $first =$ (' #first ');
var $second =$ (' #second '),
var value= $first. Val ();

4. Use var chain (single var mode)

Combining multiple VAR statements into one statement, I recommend putting unassigned variables behind.

Copy Code code as follows:

Var
$first =$ (' #first '),
$second =$ (' #second '),
Value= $first. Val (),
K=3,
Cookiestring= ' Somecookiesplease ',
I
J
myarray={};

5. Please use ' on '

In the new jQuery, the shorter on ("click") is used to replace a function like click (). In the previous version, on () is bind (). Since the JQuery 1.7 release, ON () attaches the preferred method of the event handler. However, for consistency reasons, you can simply use the on () method entirely.

Copy Code code as follows:

Bad
$first. Click (function () {
$first. CSS (' border ', ' 1px solid red ');
$first. CSS (' Color ', ' blue ');
});

$first. Hover (function () {
$first. CSS (' border ', ' 1px solid red ');
})

Copy Code code as follows:

Suggestions
$first. On (' click ', function () {
$first. CSS (' border ', ' 1px solid red ');
$first. CSS (' Color ', ' blue ');
})

$first. On (' hover ', function () {
$first. CSS (' border ', ' 1px solid red ');
})

6. Streamline JavaScript

Generally, it is best to merge functions as much as possible.

Copy Code code as follows:

Bad
$first. Click (function () {
$first. CSS (' border ', ' 1px solid red ');
$first. CSS (' Color ', ' blue ');
});

Copy Code code as follows:

Suggestions
$first. On (' click ', function () {
$first. CSS ({
' Border ': ' 1px solid red ',
' Color ': ' Blue '
});
});

7. Chain Type operation

The chain operation of the JQuery implementation method is very easy. Let's take advantage of that.

Copy Code code as follows:

Bad
$second. HTML (value);
$second. On (' click ', function () {
Alert (' Hello everybody ');
});
$second. FadeIn (' slow ');
$second. Animate ({height: ' 120px '},500);

Copy Code code as follows:

Suggestions
$second. HTML (value);
$second. On (' click ', function () {
Alert (' Hello everybody ');
}). FadeIn (' slow '). Animate ({height: ' 120px '},500);

8. Maintain the readability of the Code

Along with the streamlining of code and the use of chain-type, it may bring code difficult to read. Adding tightening and wrapping can have a good effect.

Copy Code code as follows:

Bad
$second. HTML (value);
$second. On (' click ', function () {
Alert (' Hello everybody ');
}). FadeIn (' slow '). Animate ({height: ' 120px '},500);

Copy Code code as follows:

Suggestions
$second. HTML (value);
$second
. On (' click ', function () {alert (' Hello Everybody ');})
. FadeIn (' slow ')
. Animate ({height: ' 120px '},500);


9. Select short-circuit Evaluation

Short-circuit evaluation is an expression that is evaluated from left to right, using the && (logic) or | | (logical OR) operator.

Copy Code code as follows:

Bad
function Initvar ($myVar) {
if (! $myVar) {
$myVar =$ (' #selector ');
}
}

Copy Code code as follows:

Suggestions
function Initvar ($myVar) {
$myVar = $myVar | | $ (' #selector ');
}

10. Choose a shortcut

One way to streamline code is to take advantage of coding shortcuts.

[Code]
Bad
if (Collection.length > 0) {.}

Copy Code code as follows:

Suggestions
if (collection.length) {..}

11. Separate elements in heavy operation

If you're going to do a lot of work on DOM elements (multiple attributes or CSS styles consecutively), it's recommended that you detach the elements and add them first.

Copy Code code as follows:

Bad
Var
$container =$ ("#container"),
$containerLi =$ ("#container li"),
$element =null;

$element = $containerLi.
//... A number of complex operations

Copy Code code as follows:

Suggestions
Var
$container =$ ("#container"),
$containerLi = $container. Find ("Li"),
$element =null;

$element = $containerLi. Detach ().
//... A number of complex operations

$container. Append ($element);

12. Memorizing Skills

You may have a lack of experience with the methods used in JQuery, be sure to view the documentation, and there may be a better or quicker way to use it.

Copy Code code as follows:

Bad
$ (' #id '). Data (Key,value);

Copy Code code as follows:

Recommended (efficient)
$.data (' #id ', key,value);

13. Using a subquery-Cached parent element

As mentioned earlier, DOM traversal is an expensive operation. A typical approach is to cache the parent element and reuse the cached elements when selecting child elements.

Copy Code code as follows:

Bad
Var
$container =$ (' #container '),
$containerLi =$ (' #container li '),
$containerLiSpan =$ (' #container li span ');

Copy Code code as follows:

Recommended (efficient)
Var
$container =$ (' #container '),
$containerLi = $container. Find (' Li '),
$containerLiSpan = $containerLi. Find (' span ');


14. Avoid General selectors

Putting the universal selector in the descendant selector is a bad performance.

Copy Code code as follows:

Bad
$ ('. Container > * ');

Copy Code code as follows:

Suggestions
$ ('. Container '). Children ();

15. Avoid implicit universal selectors

Universal selectors are sometimes implicit and are not easily discovered.

Copy Code code as follows:

Bad
$ ('. Someclass:radio ');

Copy Code code as follows:

Suggestions
$ ('. SomeClass input:radio ');

16. Optimization Selector

For example, ID selectors should be unique, so there is no need to add additional selectors.

Copy Code code as follows:

Bad
$ (' Div#myid ');
$ (' Div#footer a.mylink ');

Copy Code code as follows:

Suggestions
$ (' #myid ');
$ (' #footer. MyLink ');

17. Avoid multiple ID selectors

It is emphasized here that ID selectors should be unique, do not need to add additional selectors, and do not require multiple descendant ID selectors.

Copy Code code as follows:

Bad
$ (' #outer #inner ');

Copy Code code as follows:

Suggestions
$ (' #inner ');

18. Adhere to the latest version

The new version is usually better: lighter, more efficient. Obviously, you need to consider the compatibility of the code you want to support. For example, the 2.0 version does not support IE 6/7/8.

19. Discard the Discard method

It is important to focus on each new version of the deprecated method and avoid using these methods as much as possible.

Copy Code code as follows:

Bad-Live has been abandoned
$ (' #stuff '). Live (' click ', function () {
Console.log (' Hooray ');
});

Copy Code code as follows:

Suggestions
$ (' #stuff '). On (' click ', function () {
Console.log (' Hooray ');
});
Note: This may be inappropriate here, live can be implemented real-time binding, delegate may be more appropriate

20. Using CDN

Google's CND ensures that the most recent cache from the user is selected and responded quickly. (using Google CND, please search the address, this address is not available, recommend the CDN website provided by jquery).

21. Combining jQuery and JavaScript native code if necessary

As noted above, jquery is JavaScript, which means that what you can do with jquery can also be done with native code. Native code (or vanilla) may be less readable and maintainable than jQuery, and the code will be longer. But also means more efficient (usually closer to the underlying code, the more readable, the higher the performance, for example: The assembly, of course, the need for more powerful people can). Keep in mind that no frame can be smaller, lighter, and more efficient than native code (note: The test link is invalidated and the test code can be searched online).

Given the performance differences between vanilla and jquery, I strongly recommend absorbing the essence of the two, using (possibly) and jquery equivalent native code.

22. Final Advice

Finally, I recorded this article to improve the performance of jQuery and some other good advice. If you want to delve into this topic you will find a lot of fun. Remember, jQuery is not a necessity, it's just a choice. Think about why you should use it. DOM operations? Ajax? Template? CSS animation? or the selector engine? Perhaps the JavaScript mini framework or the custom version of JQuery is a better choice.

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.