38 Recommendations for jquery performance tuning

Source: Internet
Author: User
Tags bind wrapper

  Presumably everyone is familiar with jquery, the most popular JavaScript class library, and as long as the front-end developers are certainly more or less used or contacted, in this article, reference to some information and the actual use of efficiency, The principles of writing high quality jquery code will be introduced, not only to tell you how to write, but also to tell you why you write it, and hopefully you'll find it helpful.

First, note the definition of jquery variables when adding the VAR keyword this is not only jquery, all JavaScript development process, should be noted, please do not define as follows: $loading = $ (' #loading '); This is a global definition, do not know where the bad luck reference to the same variable name, will be depressed to death two, please use a var to define variables if you use more than one variable, please define the following:       Code as follows: var page = 0,     $loading = $ (' #loading '),     $body = $ (' body '); Do not add a var keyword to each variable, unless you have severe obsessive-compulsive disorder. Three, to define the jquery variable is to add the $ symbol declaration or define variables, remember if you define a jquery variable, please add a $ symbol to the variable before, as follows: The code is as follows: Var $ Loading = $ (' #loading '); The good thing about this is that you can effectively prompt yourself or other users who read your code, which is a jquery variable. Iv. DOM Operations Be sure to remember caching (cache) in the development of jquery code, we often need to manipulate dom,dom operations is a very resource consuming process, and often many people like to use jquery:   code as follows: $ (' #loading '). HTML (' finished '); $ (' #loading '). fadeout (); The code doesn't have any problems, you can also run the results normally, but notice that each time you define and call $ (' #loading '), you actually create a new variable, and if you need to reuse it, remember to define it in a variable so that you can effectively cache the variable contents as follows:   Code as follows: var $loading = $ (' #loading '); $loading. HTML (' finished '); $loading. fadeout (); This will improve performance. V. Use chain operation above example, we can write a little more concise: The code is as follows: var $loading = $ (' #loading '); $loading. HTML (' finished '). fadeout ();   VI, streamlining jquery code to try to integrate some code together, do not encode this:   code as follows://!! Villain $button. Click (function() {    $target. css (' width ', ' 50% ')     $target. CSS (' border ', ' 1px solid #202020 ');     $tar Get.css (' Color ', ' #fff '); }); It should be written like this: The   code is as follows: $button. Click (function () {    $target. css ({' width ': ' 50% ', ' border ': ' 1px solid #202020 ', ' Color ': ' #fff '}); }); Avoid using a global type selector do not write in the following way: $ ('. something > * '); This is better to write: $ ('. something '). Children (); Eight, do not stack multiple IDs do not write as follows: $ (' #something #children '); That's enough: $ (' #children '); Multi-use logic judgment | | or && to speed up. Do not write as follows: The   code is as follows: if (! $something) {    $something = $ (' #something '); write better: The code is as follows: $somet hing= $something | | $ (' #something '); Use less code to write as much as possible: if (String.Length > 0) {.} write like this: if (string.length) {.} Xi. try to use the. On method if you use a newer version of the JQuery class library, Use. On, and any other method is ultimately implemented using. On. 12, try to use the latest version of jquery jquery has better performance, but the latest version may not support IE6/7/8, so everyone needs to choose their own reality. 13. Use native JavaScript as much as possible if using native JavaScript can also implement the functionality that jquery provides, it is recommended to use native JavaScript for implementation. 14, always inherit from the #id selector This is a golden rule of the jquery selector. The quickest way for jquery to select an element is to select it with an ID.   Code as follows: $ (' #content '). Hide (); or from ID Selector inheritance to select multiple elements:   Code as follows: $ (' #content p '). Hide (); The second fastest selector in tag jquery in front of class is the tag selector (such as $ (' head '), as it is getelementbytagname () directly from the native JavaScript method. So it's always best to use tag to decorate class (and don't forget the nearest ID)   code as follows: var receivenewsletter = $ (' #nslForm input.on '); The class selector in jquery is the slowest because it iterates through all the DOM nodes in IE Explorer. Try to avoid using the class selector. Also do not use tag to decorate the ID. The following example iterates through all the DIV elements to find the node with the ID ' content ': The   code is as follows: var content = $ (' div#content '); Very slow, do not use ID to decorate the ID is also superfluous:   code as follows: var traffic_light = $ (' #content #traffic_light '); Very slowly, do not use 16, use subqueries to cache the parent object for future use     code as follows: var header = $ (' #header '); var menu = Header.find ('. Menu '); or var menu = $ ('. Menu ', header); 17, the optimization selector to apply the "right-to-left" model of sizzle since version 1.3, jquery has adopted a sizzle library, which is quite different from the previous version on the selector engine. It replaces the "right to left" model with the "left to right" model. Make sure that the right selector is specific, and the selector on the left is wider: The copy code is as follows: var linkcontacts = $ ('. Contact-links div.side-wrapper '); Instead of using the   code as follows: var linkcontacts = $ (' a.contact-links side-wrapper '); 18, using Find (), and do not use the context lookup. The finding () function is indeed faster. But if a page has many DOM nodes, it may take more time to look back: The   code is as follows: var divs = $ ('. Testdiv ', ' #pageBody '); 2353 on Firebug 3.6 var divs = $ (' #pageBody '). Find ('. Testdiv '); 2324 on Firebug 3.6-the the best time var divs = $ (' #pageBody. Testdiv '); 2469 on Firebug 3.6 19, write your own selector if you often use selectors in your code, expand jquery's $.expr[': ' Object, and write your own selector. In the following example, I created a abovethefold selector to select an element that is not visible: The   code is as follows: $.extend ($.expr[': '), { abovethefold:function (EL) {   return $ (EL). Offset (). Top < $ (window). scrolltop () + $ (window). Height ();  }}); var nonvisibleelements = $ (' div:abovethefold '); Select element 20, Cache jquery objects cache the elements you use frequently: The code is as follows: the var header = $ (' #header '); var divs = header.find (' div '); var forms = Header.find (' form ');   When Dom inserts are to be performed, all elements are encapsulated into one element   21, and direct DOM operations are slow. Change the HTML structure as little as possible.   Code as follows: var menu = ' <ul id= ' menu ' > '; for (var i = 1; i < i++) {menu + = ' <li> ' + i + ' </li> ';} menu = ' </ul> '; $ (' #header '). Prepend (menu); Do not do this: $ (' #header '). Prepend (' <ul id= ' menu ' ></ul> '); for (var i = 1; i < i++) {$ (' #menU '). Append (' <li> ' + i + ' </li> '); 22, although jquery does not throw exceptions, developers should also check objects   Although jquery does not throw a large number of exceptions to users, developers should not rely on this. jquery usually performs a lot of useless functions to determine whether an object exists. So before you make a series of references, you should check that the object exists. 23. Using direct functions instead of using the equivalent functions for better performance, you should use direct functions such as $.ajax () instead of using $.get (), $.getjson (), $.post (), because the next few will call $.ajax (). 24. Cache jquery Results for later use you will often get a Javasript Application Object-You can use the App. To save the objects you often choose for future use:     code as follows: App.hiddendivs = $ (' Div.hidden '); Then call in your application: App.hiddenDivs.find (' span '); 25, using the internal function of jquery data () to store the state do not forget to use the. Data () function to store information:   Code as follows: $ (' #head '). Data (' name ', ' value '); Then call in your application: $ (' #head '). Data (' name '); 26, using the jquery utility function do not forget the simple and practical jquery utility function. My favorite is $.isfunction (), $isArray () and $.each (). 27. Add "JS" class to HTML block when jquery is loaded, first add a class   code called "JS" to HTML: $ (' HTML '). addclass (' JS '); You can add CSS styles only when the user has JavaScript enabled. For example:   code is as follows: * * in CSS. JS #myDiv {Display:none} So when JavaScript is enabled, you can hide the entire HTML content and use jquery to implement what you want (for example, to put up some panels or expand when the user clicks on them). And when JavaScript is not enabled, the browser renders all the content, search engine crawler will also check everything. I willwill use this technique more. 28. Postpone to $ (window). Load sometimes uses $ (window). Load () ratio $ (document). Ready () is faster because the latter does not wait until all DOM elements are downloaded. You should test it before using it. 29. Use Event Delegation when you have many nodes in a container, you want to bind an event to all the nodes, delegation is suitable for this scenario. With delegation, we only need to bind the event at the parent level, and then see which child node (the target node) triggers the event. When you have a table with a lot of data, you want to set up events for the TD node, which makes it very convenient. Get the table first, then set the delegation event for all TD nodes:   Code as follows: $ ("table"). Delegate ("TD", "hover", function () {$ (this). Toggleclass (" Hover "); }); 30. Use Ready event shorthand if you want to compress the JS plugin, save every byte, you should avoid using $ (document). The Onready () code is as follows://Do not use $ (document). Ready (function () {//code}); You can be so short: $ (function () {//code}); 31, jquery Unit test test Javasript code The best way is people to test. But you can use some automated tools such as Selenium,funcunit,quit,qmock to test your code (especially plug-ins). I would like to discuss this topic on another topic because there is so much to say. 32, standardize your jquery code often standardize your code, see which query is slow, and then replace it. You can use the Firebug console. You can also use jquery's shortcut functions to make your tests easier:   Code as follows://shortcuts to record data in the Firebug console $.l (' div ');  //Get UNIX timestamp $.time ();  //Firebug record execution Code time $.lt (); $ (' div '); $.lt ();  //placing code blocks in a For loop test execution Time $.BM ("var divs = $ ('. Testdiv ', ' #pageBody ');"); 2353 on FiRebug 3.6   33, using the HMTL5 new HTML5 Standard brings a more lightweight DOM structure. A lighter structure means that using jquery requires less traversal and better load performance. So please use HTML5 if possible. 34. If you add a style to more than 15 elements, adding a style tag directly to the DOM element adds styles to a few elements, the best way is to use the Jquey CSS () function. However more than 15 more elements add styles, it is more efficient to add style labels directly to the DOM. This approach avoids the use of hard-coded (hard code) in your coding. Copy code code as follows: $ (' <style type= ' text/css ' > Div.class {color:red;} </style> '). Appendto (' head '); 35. It's a good way to avoid loading extra code in a different file with JavaScript code, just load them when you need them. This way you don't load unnecessary code and selectors. It also makes it easier to manage code. 36, compressed into a main JS file, the number of downloads to keep to the least when you have determined which files should be loaded, then package them into a file. Use some open source tools to automate your work, such as using minify (integrated with your back-end code) or using online tools like Jscompressor,yui compressor or Dean Edwards JS packer to compress your files. My favorite is jscompressor. 37. Using native Javasript to use jquery is a great thing to do, but don't forget it's also a framework for JavaScript. So you can use native JavaScript functions when the jquery code is necessary to get better performance. 38, slow loading content can not only improve load speed, but also improve SEO optimization (Lazy load content for speed and SEO benefits) use AJAX to load your site, which can save server-side loading time. You can start with a common sidebar widget.

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.