Cache variables
DOM traversal is expensive, so try to cache the elements that will be reused.
// bad h = $ (' #element '). Height (); $ (' #element '). CSS (' height ', h-20); // recommended $element = $ (' #element '= $element. Height (); $element. css (' height ', h-20);
Avoid global variables
jquery, like JavaScript, is generally preferable to ensure that your variables are within the scope of the function.
// Bad $element = $ (' #element '= $element. Height (); $element. css (' height ', h-20); // Recommended var $element = $ (' #element '); var h = $element. Height (); $element. css (' height ', h-20);
Using the Hungarian nomenclature
prefix the variable with $ to make it easy to identify the jquery object.
// Bad var first = $ (' #first '); var second = $ (' #second '); var value = $first. val (); // recommendation-Add $ prefix to jquery objects var $first = $ (' #first '); var $second = $ (' #second '),var value = $first. val ();
Using the Var chain
To combine multiple VAR statements into one statement, I recommend that you put unassigned variables behind.
var = $ (' #first '), = $ (' #second '), = $first. Val (), = 3 , = ' Somecookiesplease ', I, j, = {};
Use ' on '
in the new version of jquery, Shorter on ("click") is used to replace functions like Click (). In the previous version, on () is bind (). The preferred method of on () attaching event handlers since the jquery 1.7 release. However, for consistency reasons, you can simply use the on () method.
//Bad$first. Click (function() {$first. css (' Border ', ' 1px solid red '); $first. CSS (' Color ', ' blue ');}); $first. Hover (function() {$first. css (' Border ', ' 1px solid red ');})//Recommended$first. On (' click ',function() {$first. css (' Border ', ' 1px solid red '); $first. CSS (' Color ', ' blue ');}) $first. On (' Hover ',function() {$first. css (' Border ', ' 1px solid red ');})
Thin JavaScript
in general, it is best to combine functions as much as possible.
// oops $first. Click (function() { $first. css (' border ', ' 1px solid red '); $first. css (' color ', ' Blue ');}); // recommended $first. On (' click ',function() { $first. css ({ ' border ': ' 1px solid red ') , ' Color ': ' Blue ' }) ;
Chained operation
The chained operation of the jquery implementation method is very easy. Use this point below.
// Bad $second. HTML (value); $second. On (' click ',function() { alert (' Hello everybody ');}); $second. FadeIn (' slow '); $second. Animate ({height:' 120px '},500); // Recommended $second. HTML (value); $second. On (' click ',function() { alert (' Hello everybody ');}). FadeIn (' slow '). Animate ({height: ' 120px '},500);
Maintain the readability of your code
along with the streamlining of code and the use of chaining, the code can be difficult to read. Adding indents and line breaks can be a good result.
// Bad $second. HTML (value); $second. On (' click ',function() { alert (' Hello Everybody ') ;}). FadeIn (' slow '). Animate ({height: ' 120px '},500); // Recommended $second. HTML (value); $second . On (' click ',function() {alert (' Hello Everybody ')}) . FadeIn (' slow ') . Animate ({height:' 120px '},500);
Select short-Circuit evaluation
a short-circuit evaluation is an expression that evaluates from left to right, with && (logical AND) or | | (logical OR) operators.
// Bad function Initvar ($myVar) { if(! $myVar) { = $ (' #selector ');} } // Recommended function Initvar ($myVar) { = $myVar | | $ (' #selector ');}
Choose a shortcut
one way to streamline your code is to take advantage of coding shortcuts.
// Bad if (Collection.length > 0) {..} // Recommended if (collection.length) {..}
Separation of elements in heavy operations
If you are going to do a lot of work on DOM elements (setting multiple properties or CSS styles consecutively), it is recommended that you first detach the elements and then add them.
//Badvar$container= $ ("#container"), $containerLi= $ ("#container Li"), $element=NULL; $element=$containerLi. First ();//... Many complex operations//Bettervar$container= $ ("#container"), $containerLi= $container. Find ("Li"), $element=NULL; $element=$containerLi. First (). Detach ();//... Many complex operations$container. Append ($element);
Memorizing skills
you may have a lack of experience with the methods in jquery, be sure to review the documentation, and there may be a better or faster way to use it.
// Poor $ (' #id '). Data (key,value); // recommended (efficient)$.data (' #id ', key,value);
Using the parent element of a subquery cache
as mentioned earlier, Dom traversal is an expensive operation. A typical practice is to cache the parent element and reuse those cached elements when the child element is selected.
// Bad var = $ (' #container '), = $ (' #container Li '), = $ (' #container li span '); // recommended (efficient) var = $ (' #container '), = $container. Find (' Li '), $containerLiSpan= $ Containerli.find (' span ');
Avoid Universal selectors
It is very bad to put a generic selector in a descendant selector.
// Bad $ ('. Container > * '); // recommended $ ('. Container '). Children ();
Avoid implicit universal selectors
Universal selectors are sometimes implicit and not easily discoverable.
// Poor $ ('. Someclass:radio '); // suggested $ ('. SomeClass input:radio ');
Refine selectors
For example, the ID selector should be unique, so there is no need to add additional selectors.
// Poor $ (' Div#myid '); $ (' div#footer a.mylink '); // suggested $ (' #myid '); $ (' #footer. MyLink ');
Stick to the latest version
The new version is usually better: more lightweight and 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. Discard deprecated methodsIt is important to focus on each new version of the deprecated method and avoid using these methods as much as possible.
// bad-Live is obsolete function () { console.log (' Hooray ');}); // Recommended function () { console.log (' Hooray ');}); // Note: It may be inappropriate here, real-time binding for live can be, delegate may be more appropriate
Leveraging CDN
CND can ensure that the most recent cache is selected from the user and responds quickly, recommending a CDN from the jquery website. Combine jquery and JavaScript native code if necessary
as mentioned above, jquery is JavaScript, which means that what you can do with jquery can also be done using native code. Native code (or vanilla) may be less readable and maintainable than jquery, and the code is longer. But it also means more efficient (often closer to lower-level code readability and higher performance, for example: compilation, which of course requires more powerful talent). Original link:http://www.codeceo.com/article/jquery-coding-high-qulity.htmlTranslation Links:http://www.ctolib.com/topics-101800.html
Some techniques in jquery coding