Compile better jQuery code

Source: Internet
Author: User

This is an article about jQuery. Many articles have been written here to discuss the performance of jQuery and JavaScript. However, in this article, I plan to summarize some tips and suggestions for improving your jQuery and JavaScript code. Better code means faster applications, Fast Rendering and responsiveness means a better user experience. First, remember that jQuery is also javascript, which means we need to use the same encoding rules and Style Guide for jQuery and javascript, as well as best practices. In addition, if you are a beginner of javascript, I suggest you read the JavaScript best practices for beginners and writing high quality JavaScript articles before starting jQuery. If you have already started using jQuery, I strongly recommend following the following suggestions: caching variable DOM traversal is very expensive, so try to cache some variables that may be used again. // Bad h = fill ('height', h-20); // good $ element =$ ('# element'); h = element.height();$element.css ('height', h-20 ); avoid using global variables like using javascript. Make sure that your variables are within the scope of your function. // Bad $ element = $ ('# element'); h = element.height(;;$element.css ('height', h-20); // good var $ element = $ (' # element '); var h = elemelement.height();$element.css ('height', h-20); add a $ sign before the variable using the Hungarian name method, it is easy to see that this is a jQuery variable. // Bad var first = $ ('# first'); var second = $ ('# second'); var value = $ first. val (); // better-we use to put $ symbol before jQuery-manipulated objects var $ first = $ ('# first '); var $ second = $ ('# second'), var value = $ first. val (); use Var chain (single Var mode). Do not use multiple var declarations. You can combine them into a var Declaration. We recommend that you put variables without specified values at the end. Var $ first = $ ('# first'), $ second = $ ('# second'), value = $ first. val (), k = 3, cookiestring = 'somecookiesplease', I, j, myArray = {}; it is best to use jQuery to bind the latest version of the event on to have clicked () changed to the abbreviation of the function on ('click. In earlier versions, click () is short for bind (). In jQuery 1.7, on () is the preferred method for appending event handlers. However, for consistency, you can simply use on (). // Bad condition first.click(function(condition condition parameter first.css ('border', '1px solid red'condition parameter first.css ('color', 'blue');}); condition ('border ', '1px solid red');}) // loads ('border', '1px solid red'{}{first.css ('color', 'blue');}) loads ('border ', '1px solid red');}) compress and streamline javascript. In general, we need to merge functions as much as possible // bad $ first. click (function () {$ First.css ('border', '1px solid red' specify parameter first.css ('color', 'blue') ;}); // better trim ({'border': '1px solid red ', 'color': 'blue'}) ;}; Using Chained operations according to the above rules, jQuery can easily link methods together. We need to take advantage of this advantage. // Bad seconds second.html (value); $ second. on ('click', function () {alert ('Hello everybody') ;}); $ second. fadeIn ('low'); $ second. animate ({height: '120px '}, 500); // better extends second.html (value); $ second. on ('click', function () {alert ('Hello everybody ');}). fadeIn ('low '). animate ({height: '120px '}, 500); Keep the code readable. When javascript code is simplified and chained operations are used, your code sometimes becomes unreadable, try to use indentation and line breaks to make the code more beautiful. // Bad seconds second.html (value); $ second. on ('click', function () {alert ('Hello everybody ');}). fadeIn ('low '). animate ({height: '120px '}, 500); // better extends second.html (value); $ second. on ('click', function () {alert ('Hello everybody ');}). fadeIn ('low '). animate ({height: '120px '}, 500); Short-circuit is used to evaluate the short-circuit value from left to right) or | (logical or) operator. // Bad function initVar ($ myVar) {if (! $ MyVar) {$ myVar = $ ('# selector') ;}// better function initVar ($ myVar) {$ myVar = $ myVar | $ ('# selector');} One of the shortcuts to streamline code is to use some encoding shortcuts. // Bad if (collection. length> 0 ){..} // better if (collection. length ){..} complex operations require separation of elements. If you perform a large number of operations on DOM elements (multiple attributes or css styles are set consecutively), we recommend that you first separate the elements and then add them. // Bad var $ container = $ ("# container"), $ containerLi = $ ("# container li"), $ element = null; $ element = $ containerLi. first ();//... a lot of complicated things // better var $ container =$ ("# container"), $ containerLi = $ container. find ("li"), $ element = null; $ element = $ containerLi. first (). detach ();//... a lot of complicated things $ container. append ($ element) A good or faster way to use it. // Bad $ ('# id '). data (key, value); // better (faster) $. data ('# id', key, value); the parent element cached using a subquery is as mentioned earlier, and DOM traversal costs a lot, A typical practice is to cache parent elements and reuse them when selecting child elements. // Bad var $ container = $ ('# iner'), $ containerLi = $ ('# container li'), $ containerLiSpan = $ ('# container li span '); // better (faster) var $ container = $ ('# iner'), $ containerLi = $ container. find ('lil'), $ containerLiSpan = $ containerLi. find ('span '); Avoid the slow usage of common selector when used together with other selector. // Bad $ ('. container> * '); // better $ ('. container '). children (); avoid using a common selector. When you miss the selector, the common selector (*) still works/bad $ ('. someclass: radio '); // better $ ('. someclass input: radio '); Optimization selector. For example, the Id selector should be unique, so there is no need to add additional selector. // Bad $ ('div # myid'); $ ('div # footer. mylink'); // better $ ('# myid'); $ (' # footer. mylink'); Avoid Multiple ID delimiters re-emphasizing that the ID delimiters should be unique. You do not need to add additional delimiters, but do not need multiple descendant ID delimiters. // Bad $ ('# outer # inner'); // better $ ('# inner'); try to use the latest version, which 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 important not to pay attention to the discard methods of each new version and avoid using them whenever possible. /Bad-live is deprecated $ ('# stuff '). live ('click', function () {console. log ('hooray') ;}); // better $ ('# stuff '). on ('click', function () {console. log ('hooray');}); using CDN to load jQuery Google's CND ensures that the cache closest to the user is selected and responds quickly, address is a combination of jQuery and javascript native code as described in the http://code.jQuery.com/jQuery-latest.min.js when necessary, jQuery is javascript, which means that what jQuery can do can also be done with native code. The readability and maintainability of native code 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 native code. Finally, I suggest writing this article to improve jQuery's performance and provide some 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? Sometimes, the demand for customized javascript micro-framework or jQuery is also worth considering. Some suggestions for beginners

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.