Writing 19 efficient jquery code-jquery-js tutorials

Source: Internet
Author: User
It is not uncommon to discuss jQuery and javascript performance. However, I plan to summarize some speed tips and some of my own suggestions in this article to improve your jQuery and javascript code. Good code will increase the speed. Quick rendering and response means a better user experience. First, remember that jQuery is javascript in your mind. This means we should adopt the same encoding practices, style guides and best practices.
First of all, if you are a beginner in javascript, I suggest you read "24 best practices for beginners of JavaScript". This is a high-quality javascript tutorial. You 'd better read it before getting started with jQuery.
When you are about to use jQuery, I strongly recommend that you follow these guidelines:
1. cache Variables
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 );


2. 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 );


3. Use 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 ();


4. 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 = {};


5. 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 ');
})


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

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


7. Chain Operations
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 );


8. 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 );


9. Select short-circuit Evaluation
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 ');
}


10. Select shortcuts
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 ){..}


11. 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 );


12. 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 );


13. Use a subquery to cache the parent Element
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 ');


14. 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.

// 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.

// Bad

$ ('P # myid ');
$ ('P # footer a. mylink ');

// Suggestions
$ ('# Myid ');
$ ('# Footer. myLink ');


15. Avoid Multiple ID delimiters
It is emphasized that ID delimiters should be unique and no additional delimiters need to be added, and multiple descendant ID delimiters are not required.

The Code is as follows:


// Bad

$ ('# Outer # inner ');

// Suggestions

$ ('# Inner ');


16. 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.

Abandon the discard Method
It is very important to pay attention to the obsolete methods of each new version and try to avoid using these methods.

The Code is as follows:


// Bad-the live has been deprecated

$ ('# Stuff'). live ('click', function (){
Console. log ('hooray ');
});

// Suggestions
$ ('# Stuff'). on ('click', function (){
Console. log ('hooray ');
});


// Note: This may be inappropriate because live can be bound in real time, and delegate may be more suitable.
17. 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 ).

18. 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 native code.

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.

19. 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.

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.