19 Guidelines for writing efficient jquery code

Source: Internet
Author: User
Tags deprecated readable advantage

  Discussion of jquery and JavaScript performance is not uncommon. However, in this article I plan to summarize some of the speed techniques and some of my own suggestions to improve your jquery and JavaScript code. Good code can lead to a speed boost. Fast rendering and response means a better user experience

First, keep in mind that jquery is JavaScript. This means that we should adopt the same coding conventions, style guides and best practices. First of all, if you're a beginner of JavaScript, I suggest you read the 24 best practices for JavaScript beginners, a high-quality JavaScript tutorial that you should read before you touch jquery. When you are ready to use jquery, I strongly recommend that you follow these guidelines: 1. Cache variables DOM traversal is expensive, so try to reuse the element cache.     Code as follows://bad   H = $ (' #element '). Height (); $ (' #element '). CSS (' height ', h-20);  //Recommendation   $element = $ (' #element '); h = $element. Height (); $element. css (' height ', h-20);   2. Avoid global variables jquery, like JavaScript, in general, it's best to make sure that your variables are within the scope of the function.   Code as follows://bad   $element = $ (' #element '); h = $element. Height (); $element. css (' height ', h-20);  //Recommendation   var $element = $ (' #element '); var h = $element. Height (); $element. css (' height ', h-20);   3. Use the Hungarian nomenclature to prefix the variable with $ to facilitate the identification of the jquery object.   Code as follows://Poor   Var-a (' #first '); var second = $ (' #second '); var value = $first. val ();  /suggestion-add $ prefix   var $first = $ (' #first ') in jquery object; var $second = $ (' #second '), var value = $first. val ();   4. To combine multiple VAR statements into one statement using the Var chain (single var mode), I recommend putting unassigned variables behind. The code is as follows: var    $first = $ (' #first '),   $second = $ (' #second '),   value = $first. val (),   k = 3,   C ookiestring = ' somecookiesplease ',   I,   j,   myarray = {}; 5. Use ' on ' in new jquery, Shorter on ("click") to replace a function like click (). In the previous version, on () is bind (). Since the jquery 1.7 release, ON () attaches the preferred method of the event handler. However, for consistency reasons, you can simply use the on () method entirely. The code is as follows://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 ', fun Ction () {    $first. CSS (' border ', ' 1px solid red ');     $first. CSS (' Color ', ' blue ');   $first. On (' hover ', function () {    $first. CSS (' border ', ' 1px solid Red ');}   6. Compact JavaScript Generally speaking, It is best to merge functions as much as possible.   Code as follows://Bad   $first. Click (function () {    $first. CSS (' border ', ' 1px solid red ');     $first . css (' Color ', ' blue '); });  // Suggestions   $first. On (' click ', Function () {    $first. css ({      ' border ': ' 1px solid red ',         ' color ': ' Blue '    } '; });   7. Chained operation of the jquery implementation method is very easy. Let's take advantage of that. The code is as follows://Bad   $second. html (value); $second. On (' click ', Function () {    alert (' Hello Everybody ');}); $second. FadeIn (' slow '); $second. Animate ({height: ' 120px '},500);  //Recommendation   $second. HTML (value); $second. On (' click ', Function () {    alert (' Hello Everybody ');}). FadeIn (' slow '). Animate ({height: ' 120px '},500);   8. Maintaining the readability of your code, along with the streamlining of code and the use of chains, can lead to difficult reading of code. Adding tightening and wrapping can have a good effect. The code is as follows://Bad   $second. html (value); $second. On (' click ', Function () {    alert (' Hello Everybody ');}). FadeIn (' slow '). Animate ({height: ' 120px '},500);  //Recommendation   $second. HTML (value); $second    . On (' click ', function () {alert (' Hello Everybody ');})    . FadeIn (' slow ')     Imate ({height: ' 120px '},500);   9. Select short-circuit evaluation Short-circuit evaluation is an expression that is evaluated from left to right, using the && (logic) or | | (logical OR) operator. The code is as follows://bad   function Initvar ($myVar) {    if (! $myVar) {        $myVar = $ (' #selecto R ');    }  //recommended   function Initvar ($myVar) {    $myVar = $myVar | | $ (' #selector ');}   10. One way to select shortcuts for streamlining code is to take advantage of coding shortcuts. The code is as follows://Bad   if (Collection.length > 0) {.}  //recommendation   if (Collection.length) {.}   11. Heavy operations separating elements if you To do a lot of work on DOM elements (multiple properties or CSS styles consecutively), it is recommended that you detach the element first and then add it. The code is as follows://bad   var      $container = $ ("#container"),     $containerLi = $ ("#container Li"),     $element = null;   $element = $containerLi.; //... Many complex operations  //better   var      $container = $ ("#container"),     $containerLi = $contai Ner.find ("Li"),     $element = null;   $element = $containerLi. Detach (); //... Many complex operations   $container. Append ($element);   12. Memorizing skills you may be using JqueRy method lacks experience, be sure to view the document and there may be a better or quicker way to use it. The code is as follows://Bad   $ (' #id '). Data (Key,value);  //suggestion (efficient)   $.data (' #id ', key,value);   13. Parent element with subquery caching as mentioned earlier, Dom traversal is an expensive operation. A typical approach is to cache the parent element and reuse the cached elements when selecting child elements. The code is as follows://bad   var      $container = $ (' #container '),     $containerLi = $ (' #container Li '),     $containerLiSpan = $ (' #container Li span ');  //suggestion (efficient)   var      $container = $ (' #container '),     $containerLi = $container. Fi nd (' li '),     $containerLiSpan = $containerLi. Find (' span ');   14. Avoid the common selector to put the universal selector in the descendant selector, the performance is very bad. The code is as follows://Bad   $ ('. Container > * ');   //Recommendation   $ ('. Container '). Children (); Avoiding implicit universal selectors is sometimes implicit and not easy to discover.  //Poor   $ ('. Someclass:radio ');   //Recommendation   $ ('. SomeClass input:radio '); Optimization selectors for example, ID selectors should be unique, so there is no need to add additional selectors.  //Poor   $ (' Div#myid ');  $ (' div#footer a.mylink ');  //Proposal $ (' #myid '); $ (' #footer. MyLink '); &nbsP 15. Avoid multiple ID selectors in this emphasis, ID selector should be unique, do not need to add additional selectors, not to require multiple descendant ID selectors. Copy code code as follows://Bad   $ (' #outer #inner ');   //Recommendation   $ (' #inner ');   16. Sticking to the latest version of the new version is usually better: lighter, 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.   Discarding methods to focus on each new version of deprecated methods is important and avoids using these methods as much as possible.   Code as follows://bad-live has been deprecated   $ (' #stuff '). Live (' click ', Function () {  Console.log (' Hooray ');});  //Proposal $ (' #stuff '). On (' click ', Function () {  Console.log (' Hooray ');});  //Note: This may not be the case, the live can achieve real-time binding, delegate may be more appropriate 17. Using CDN Google's CND can ensure that the most recent cache from the user and respond quickly. (using Google CND, please search the address, this address is not available, recommend the CDN website provided by jquery).   18. Combining jquery and JavaScript native code when necessary as described above, jquery is JavaScript, which means that what you can do with jquery can also be done with native code. Native code (or vanilla) may be less readable and maintainable than jquery, and the code will be longer. But also means more efficient (usually closer to the underlying code, the more readable, the higher the performance, for example: The assembly, of course, the need for more powerful people can). Keep in mind that no frame can be smaller, lighter, and more efficient than native code   given the performance differences between vanilla and jquery, I strongly recommend absorbing the essence of two people, using (possible) and jquery equivalent native code.   19. Last advice Finally, I recorded this article to improve the performance of jquery and some other good advice. If you want to delve into this topic you will find a lot of fun. Remember, jquery is not a necessity, it's just a choice. Think about why you should use it. Dom operations? Ajax? Template? CSS animation? or the selector engine? Perhaps JavaA custom version of the script miniature frame or jquery is a better choice.

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.