Efficient jQuery coding skills and jQuery coding skills
Cache variable
DOM traversal is expensive, so we try to cache elements that will be reused.
1 // bad 2 h = $ ('# element '). height (); 3 values ('{element'}.css ('height', h-20); 4 5 // recommended 6 $ element = $ ('# elements'); 7 h = $ element. height (); 8 rows 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.
1 // bad 2 $ element = $ ('# element'); 3 h = $ element. height (); 4 $element.css ('height', h-20); 5 6 // suggested 7 var $ element = $ ('# element'); 8 var h = $ element. height (); 9 rows element.css ('height', h-20 );
Using the Hungarian naming method
Add a $ prefix to the variable to identify the jQuery object.
1 // bad 2 var first = $ ('# first'); 3 var second = $ ('# second'); 4 var value = $ first. val (); 5 6 // recommended-add $ prefix 7 var $ first = $ ('# first') before the jQuery object '); 8 var $ second = $ ('# second'), 9 var value = $ first. val ();
Use Var chain (single Var mode)
Merge multiple var statements into one statement. I suggest placing unassigned variables behind it.
1 var2 $first = $('#first'),3 $second = $('#second'),4 value = $first.val(),5 k = 3,6 cookiestring = 'SOMECOOKIESPLEASE',7 i,8 j,9 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.
1 // bad 2 $ first. click (function () {3 then first.css ('border', '1px solid red'); 4 then first.css ('color', 'blue'); 5 }); 6 7 $ first. hover (function () {8 rows first.css ('border', '1px solid red'); 9}) 10 11 // We recommend 12 $ first. on ('click', function () {13 rows first.css ('border', '1px solid red'); 14 rows first.css ('color', 'blue'); 15 }) 16 17 $ first. on ('hover ', function () {18 rows first.css ('border', '1px solid red'); 19 })
Simplified javascript
In general, it is best to merge functions as much as possible.
1 // bad 2 $ first. click (function () {3 then first.css ('border', '1px solid red'); 4 then first.css ('color', 'blue'); 5 }); 6 7 // We recommend 8 $ first. on ('click', function () {9 specify first.css ({10 'border': '1px solid red', 11 'color': 'blue' 12 }); 13 });
Chain Operation
The chain operation of jQuery implementation method is very easy. This is used below.
1 // bad 2 bytes second.html (value); 3 $ second. on ('click', function () {4 alert ('Hello everybody'); 5}); 6 $ second. fadeIn ('low'); 7 $ second. animate ({height: '120px '}, 500); 8 9 // 10 seconds second.html (value); 11 $ second. on ('click', function () {12 alert ('Hello everbody'); 13 }). fadeIn ('low '). 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.
1 // bad 2 bytes second.html (value); 3 $ second. on ('click', function () {4 alert ('Hello everbody'); 5 }). fadeIn ('low '). animate ({height: '120px '}, 500); 6 7 // We recommend 8 seconds second.html (value); 9 $ second10. on ('click', function () {alert ('Hello everybody');}) 11. fadeIn ('low') 12. 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.
1 // bad 2 function initVar ($ myVar) {3 if (! $ MyVar) {4 $ myVar =$ ('# selector'); 5} 6} 7 8 // We recommend 9 function initVar ($ myVar) {10 $ myVar = $ myVar | $ ('# selector'); 11}
Shortcut Selection
One of the ways to streamline code is to use short-cut encoding.
1 // bad 2 if (collection. length> 0) {...} 3 4 // 5 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.
1 // bad 2 var 3 $ container =$ ("# container"), 4 $ containerLi =$ ("# container li"), 5 $ element = null; 6 $ element = $ containerLi. first (); 7 //... many complex operations 8 9 // better10 var11 $ container =$ ("# container"), 12 $ containerLi = $ container. find ("li"), 13 $ element = null; 14 $ element = $ containerLi. first (). detach (); 15 //... many complex operations 16 $ 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.
1 // terrible 2 $ ('# id '). data (key, value); 3 4 // recommended (efficient) 5 $. 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.
1 // bad 2 var 3 $ container =$ ('# iner'), 4 $ containerLi =$ ('# container li '), 5 $ containerLiSpan = $ ('# container li span'); 6 7 // recommended (efficient) 8 var 9 $ container = $ ('# iner '), 10 $ containerLi = $ container. find ('lil'), 11 $ containerLiSpan = $ containerLi. find ('span ');
Avoid common Selector
Put the common selector in the descendant selector, and the performance is very bad.
1 // terrible 2 $ ('. iner> *'); 3 4 // recommended 5 $ ('. iner'). children ();
Avoid implicit common Selector
The common selector is sometimes implicit and is not easy to find.
1 // terrible 2 $ ('. someclass: radio'); 3 4 // recommended 5 $ ('. someclass input: radio ');
Optimized Selection character
For example, the Id selector should be unique, so there is no need to add additional selector.
// Bad $ ('div # myid'); $ ('div # footer. mylink'); // recommended $ ('# 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.
1 // terrible 2 $ ('# outer # inner'); 3 4 // recommended 5 $ ('# 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.
1 // bad-live has been abandoned 2 $ ('# stuff '). live ('click', function () {3 console. log ('hooray'); 4}); 5 6 // suggested 7 $ ('# stuff '). on ('click', function () {8 console. log ('hooray'); 9}); 10 // note: this error may be inappropriate because live can be bound in real time. delegate may be more appropriate.
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. JQuery is also a common front-end development language, and there are also many development tools that support JavaScript. For example, SpreadJS is an enterprise-level JavaScript Spreadsheet control that can integrate workbooks, data visualization, and computing functions into JavaScript Web applications. Original article: Workshop