Tips for Writing Efficient JSLite code like JQuery _ jquery

Source: Internet
Author: User
This article mainly introduces some tips for writing efficient JSLite code like JQuery. This Article plans some speed tips and suggestions based on others' summary of jQuery, it is not uncommon for anyone who wants to learn how to improve your JSLite and javascript code. However, I plan to teach you how to improve your JSLite and javascript code based on some speed tips and suggestions summarized by others for jQuery. Good code will increase the speed. Quick rendering and response means a better user experience.

First, keep in mind that JSLite is javascript. This means we should adopt the same encoding practices, style guides and best practices.

First of all, if you are a beginner in javascript and have never used jQuery, I suggest you read the syntax of the official document first. this is a high-quality javascript tutorial, it indicates that you have used jQuery for a while.

When you are about to use JSLite, I strongly recommend that you follow these guidelines:

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

JSLite 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 JSLite object.

The code is as follows:


// Bad
Var first = $ ('# first ');
Var second = $ ('# second ');
Var value = $ first. val ();
// Recommended-add the $ prefix to the JSLite 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 JSLite, the shorter on ("click") is used to replace functions such as click. In earlier versions, on () is bind (). The preferred method for attaching an event handler 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.

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

JSLite implementation method chain operations are 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 JSLite 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 ');


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


Stick to the latest version

The new version is usually better: it is more lightweight, more efficient, more methods, and more comprehensive coverage of the jQuery method. Obviously, you need to consider the code compatibility you want to support. For example, whether the project runs well in support of HTML5/CSS3

Combine JSLite and javascript Native code if necessary

As mentioned above, JSLite is javascript, which means that what JSLite can do can also be done using native code. The readability and maintainability of native code may not be as good as that of JSLite, 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 ).

Last piece of advice

Finally, I recorded this article to improve JSLite performance and other good suggestions. If you want to study this topic in depth, you will find a lot of fun. Remember, JSLite is not an indispensable choice. Think about why you want to use it. DOM operation? Ajax? Template? Css animation? Or selector? JQuery heavy developer?

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.