Tips for improving jQuery performance _ jquery

Source: Internet
Author: User
This article focuses on in-depth introduction to jQuery's performance optimization techniques. If you need it, you can refer to the following tips to improve jQuery's performance optimization:

Cache variable
DOM traversal is expensive, so we try to cache elements that will be reused.

The Code is as follows:


// Bad
H = $ ('# element'). height ();
(('{Element'{.css ('height', h-20 );
// Suggestions
$ Element = $ ('# element ');
H = $ element. height ();
$Element.css ('height', h-20 );

Avoid global variables
JQuery is the same as javascript. In general, it is best to ensure that your variables are within the function scope.

The Code is as follows:


// Bad
$ Element = $ ('# element ');
H = $ element. height ();
$Element.css ('height', h-20 );
// Suggestions
Var $ element = $ ('# element ');
Var h = $ element. height ();
$Element.css ('height', h-20 );

Using the Hungarian naming method
Add a $ prefix to the variable to identify the jQuery object.

The Code is as follows:


// Bad
Var first = $ ('# first ');
Var second = $ ('# second ');
Var value = $ first. val ();
// Recommended-Add the $ prefix before the jQuery object
Var $ first = $ ('# first ');
Var $ second = $ ('# second '),
Var value = $ first. val ();

Use Var chain (single Var mode)
Merge multiple var statements into one statement. I suggest placing unassigned variables behind it.

The Code is as follows:


Var
$ First = $ ('# first '),
$ Second = $ ('# second '),
Value = $ first. val (),
K = 3,
Cookiestring = 'somecookiesplease ',
I,
J,
MyArray = {};

Use 'on'
In the new version of jQuery, the shorter on ("click") is used to replace functions such as click. In earlier versions, on () is bind (). Since jQuery 1.7, the preferred method for attaching event handlers to on. However, for consistency, you can simply use the on () method.

The Code is as follows:


// Bad
$ First. click (function (){
Define first.css ('border', '1px solid red ');
Define first.css ('color', 'blue ');
});
$ First. hover (function (){
Define first.css ('border', '1px solid red ');
})
// Suggestions
$ First. on ('click', function (){
Define first.css ('border', '1px solid red ');
Define first.css ('color', 'blue ');
})
$ First. on ('hover ', function (){
Define first.css ('border', '1px solid red ');
})

Simplified javascript
In general, it is best to merge functions as much as possible.

// Bad
$ First. click (function (){
Define first.css ('border', '1px solid red ');
Define first.css ('color', 'blue ');
});
// Suggestions
$ First. on ('click', function (){
$First.css ({
'Border': '1px solid red ',
'Color': 'blue'
});
});

The Code is as follows:


// Bad
$ First. click (function (){
Define first.css ('border', '1px solid red ');
Define first.css ('color', 'blue ');
});
// Suggestions
$ First. on ('click', function (){
$First.css ({
'Border': '1px solid red ',
'Color': 'blue'
});
});

Chain Operation
The chain operation of jQuery implementation method is very easy. This is used below.

The Code is as follows:


// Bad
$Second.html (value );
$ Second. on ('click', function (){
Alert ('Hello everbody ');
});
$ Second. fadeIn ('slow ');
$ Second. animate ({height: '120px '}, 500 );
// Suggestions
$Second.html (value );
$ Second. on ('click', function (){
Alert ('Hello everbody ');
}). FadeIn ('slow'). animate ({height: '120px '}, 500 );

Maintain code readability
While streamlining code and using the chain, it may make the code hard to read. Adding a thumbnail and a line feed can have a good effect.

The Code is as follows:


// Bad
$Second.html (value );
$ Second. on ('click', function (){
Alert ('Hello everbody ');
}). FadeIn ('slow'). animate ({height: '120px '}, 500 );
// Suggestions
$Second.html (value );
$ Second
. On ('click', function () {alert ('Hello everybody ');})
. FadeIn ('slow ')
. Animate ({height: '120px '}, 500 );

Select short-circuit evaluate
Short-circuit evaluate is a left-to-right evaluate expression, using the & (logical and) or | (logical or) operator.

The Code is as follows:


// Bad
Function initVar ($ myVar ){
If (! $ MyVar ){
$ MyVar = $ ('# selector ');
}
}
// Suggestions
Function initVar ($ myVar ){
$ MyVar = $ myVar | $ ('# selector ');
}

Shortcut Selection
One of the ways to streamline code is to use short-cut encoding.

The Code is as follows:


// Bad
If (collection. length> 0 ){..}
// Suggestions
If (collection. length ){..}

Separation of elements in heavy operations
If you want to perform a large number of operations on DOM elements (consecutively setting multiple attributes or css styles), we recommend that you first separate the elements and then add them.

The Code is as follows:


// Bad
Var
$ Container = $ ("# container "),
$ ContainerLi = $ ("# container li "),
$ Element = null;
$ Element = $ containerLi. first ();
//... Many complex operations
// Better
Var
$ Container = $ ("# container "),
$ ContainerLi = $ container. find ("li "),
$ Element = null;
$ Element = $ containerLi. first (). detach ();
//... Many complex operations
$ Container. append ($ element );

Memorizing skills
You may not have any experience in using jQuery methods. You must check the document. There may be a better or faster way to use it.

The Code is as follows:


// Bad
$ ('# Id'). data (key, value );
// Recommended (efficient)
$. Data ('# id', key, value );

Parent element cached by subquery
As mentioned above, DOM traversal is an expensive operation. A typical practice is to cache parent elements and reuse them when selecting child elements.

The Code is as follows:


// Bad
Var
$ Container = $ ('# iner '),
$ ContainerLi = $ ('# container li '),
$ ContainerLiSpan = $ ('# container li span ');
// Recommended (efficient)
Var
$ Container = $ ('# iner '),
$ ContainerLi = $ container. find ('lil '),
$ ContainerLiSpan = $ containerLi. find ('span ');

Avoid common Selector
Put the common selector in the descendant selector, and the performance is very bad.

The Code is as follows:


// Bad
$ ('. Iner> *');
// Suggestions
$ ('. Iner'). children ();

Avoid implicit common Selector
The common selector is sometimes implicit and is not easy to find.

The Code is as follows:


// Bad
$ ('. Someclass: radio ');
// Suggestions
$ ('. Someclass input: radio ');

Optimized Selection character
For example, the Id selector should be unique, so there is no need to add additional selector.

The Code is as follows:


// Bad
$ ('P # myid ');
$ ('P # footer a. mylink ');
// Suggestions
$ ('# Myid ');
$ ('# Footer. myLink ');

To avoid multiple ID delimiters, the ID delimiters must be unique. You do not need to add additional delimiters or multiple descendant ID delimiters.

The Code is as follows:


// Bad
$ ('# Outer # inner ');
// Suggestions
$ ('# Inner ');

Stick to the latest version
The new version is usually better: lighter and more efficient. Obviously, you need to consider the code compatibility you want to support. For example, version 2.0 does not support ie 6/7/8. It is very important to discard the discard method and follow the discard method of each new version, and avoid using these methods as much as possible.

The Code is as follows:


// Bad
$ ('# Outer # inner ');
// Suggestions
$ ('# Inner ');

Use CDN
Google's CND ensures that the cache closest to the user is selected and responds quickly. (If you use Google CND, please search for the address by yourself. The address here cannot be used. We recommend that you use the CDN provided on the official jquery website ).

Combine jQuery and javascript native code if necessary
As mentioned above, jQuery is javascript, which means that what jQuery can do can also be done using native code. The readability and maintainability of native code (or vanilla) may be inferior to that of jQuery, and the code is longer. But it also means more efficient (usually closer to the lower-Layer Code, the lower the readability, the higher the performance, for example: Assembly, of course, more powerful talent is needed ). Remember that no framework can be smaller, lighter, and more efficient than the native code (Note: The test link has expired and you can search for the test code online ). In view of the performance differences between vanilla and jQuery, I strongly suggest absorbing the essence of both, using (if possible) native code equivalent to jQuery.

Last piece of advice
Finally, I recorded this article to improve jQuery's performance and other good suggestions. If you want to study this topic in depth, you will find a lot of fun. Remember, jQuery is not an indispensable choice. Think about why you want to use it. DOM operation? Ajax? Template? Css animation? Or is the selection engine? Maybe javascript micro-framework or jQuery's customized version is a better choice.

The above is a detailed introduction to improving jQuery's performance optimization. I hope it will be helpful to you.

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.