JQuery coding standards and best practices

Source: Internet
Author: User
Tags coding standards

I don't know where I saw this article about jQuery encoding. It's very practical. I just recently studied the basic knowledge of jQuery. Today, I open my favorites to translate the original article, however, the content is very practical and may have been translated by a great god. You just need to check the essence. Loading jQuery 1. Use CDN to load jQuery on the page as much as possible. CDN Benefits, some popular CDN addresses <script type = "text/javascript" <br> src = "// ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script> <script> window. jQuery | document. write ('<script src = "js/jquery-1.11.0.min.js" <br> type = "text/javascript"> <\/script>') </script> 2. it is best to provide a jQuery library of the same version as the CDN locally, as shown above. More details 3. Use the url of protocol-relative/protocol-independent (remove http: And https :), as shown above. 4. Try to keep your javascript and jQuery code at the bottom of the page. More information and examples of HTML5 sample files. 5. Which version should I use? If IE6/7/8 is supported, do not use version 2.x. For new web-apps, if you do not have plug-in compatibility problems, we strongly recommend that you use the latest version of jQuery. When you load jQuery from CDN, You need to specify the complete jQuery version number you want to load (for example, 1.11.0 cannot be written as 1.11 or 1 ). Do not load multiple different versions of jQuery. 6. if you want to use other libraries, such as Prototype, MooTools, and Zapto, which also use the $ symbol, do not use $ to call jQuery functions. Use jQuery instead of $. You can also return $ controller to other libraries through $. onConfilict. 7. Multiple new features of the browser are detected using Modernizr. JQuery variables 1. All variables used to store/cache jQuery objects should have a prefix $. 2. cache the content returned by the jQuery selector in the variable for reuse. <Br> var $ myDiv = $ ("# myDiv"); $ myDiv. click (function (){...}); <br> 3. use the hump rule to name variables. Selector 1. Use ID whenever possible, which is faster because it uses document. getElementById () for processing. 2. When using a class selector, do not specify the element type in the class selector. Performance Comparison var $ products =$ ("div. products "); // SLOWvar $ products = $ (". products "); // FAST3. Use find to find nested selectors such as id-> child. The find () method is faster because the first selector (id) won't be processed by Sizzle. For more details, see. // BAD, a nested query for Sizzle selector enginevar $ productIds = $ ("# products div. id "); // GOOD, # products is already selected by document. getElementById () so only div. id needs to go through Sizzle selector enginevar $ productIds =$ ("# products "). find ("div. id "); 4. try to be as detailed as possible on the right side of your selector. Try to be as simple as possible on the left side and provide more information. // Unoptimized $ ("div. data. gonzarez "); // Optimized $ (". data td. gonzarez "); 5. avoid excessive details, more details, and performance comparison. $ (". Data table. attendees td. gonzarez "); // Better: Drop the middle if possible. $ (". data td. gonzarez "); 6. give the selector a context. // SLOWER because it has to traverse the whole DOM. class $ ('. class '); // FASTER because now it only looks under class-container. $ ('. class ',' # class-iner '); 7. avoid using the common selector *. More information $ ('div. container> * '); // BAD $ ('div. container '). children (); // BETTER8. avoid using implicit generic selector. When you miss out some selectors, the general selector (*) still exists implicitly. More information $ ('div. someclass: radio '); // BAD $ ('div. someclass input: radio '); // GOOD9. do not specify multiple IDs when using IDs. The ID selector uses the document. getElementById () is processed, so do not mix it with other choices. $ ('# Outer # inner'); // BAD $ ('div # inner '); // BAD $ ('. outer-container # inner '); // BAD $ (' # inner '); // GOOD, only calldocument. getElementById () DOM Operation Processing 1. before processing the DOM, you must detach an existing element and then remove it. For more information, see var $ myList = $ ("# list-container> ul "). detach ();//... a lot of complicated things on $ myList. appendTo ("# list-container"); 2. use string connection or array. do not use append () for join (). For more details, see performance comparison. // BADvar $ myList = $ ("# list"); for (var I = 0; I <10000; I ++) {$ myList. append ("<li>" + I + "</li>");} // GOODvar $ myList = $ ("# list"); var list = ""; for (var I = 0; I <10000; I ++) {list + = "<li>" + I + "</li>" too many tables mylist.html (list ); // EVEN FASTERvar array = []; for (var I = 0; I <10000; I ++) {array [I] = "<li>" + I + "</li>"; using arrays mylist.html (array. join (''); 3. do not operate on nonexistent elements. For more details, // BAD: This runs three functions before it realizes there's nothing in the selection $ ("# nosuchthing "). slideUp (); // GOODvar $ mySelection = $ ("# nosuchthing"); if ($ mySelection. length) {$ mySelection. slideUp ();} Event 1. only the ready event processing function of one document is used on each page. This makes debugging and action tracking easier. 2. Do not use anonymous functions to bind events. Anonymous functions are difficult to debug, maintain, test, and reuse. More details $ ("# myLink "). on ("click", function (){...}); // BAD // GOODfunction myLinkClickHandler (){...} $ ("# myLink "). on ("click", myLinkClickHandler); 3. do not use anonymous functions for callback for processing ready events. At one time, it was difficult to debug, maintain, test, and reuse anonymous functions. $ (Function (){...}); // BAD: You can never reuse or write a test for this function. // GOOD $ (initPage); // or $ (document ). ready (initPage); function initPage () {// Page load event where you can initialize values and call other initializers .} 4. the ready event handler should be included in the external javascript file, and the inline javascript should call the handler directly after initialization. <Script src = "my-document-ready.js"> </script> <script> // Any global variable set-up that might be needed. $ (document ). ready (initPage); // or $ (initPage); </script> 5. do not write javascript Inline code in HTML, which is a nightmare for debugging. Using jQuery to bind events makes it easy to dynamically add and remove events. <A id = "myLink" href = "#" onclick = "myEventHandler ();"> my link </a> <! -- BAD --> $ ("# myLink "). on ("click", myEventHandler); // GOOD6. Add a namespace for the event as much as possible, so that it is easy to remove events you have bound without affecting other bound events. $ ("# MyLink "). on ("click. mySpecialClick ", myEventHandler); // GOOD // Later on, it's easier to unbind just your click event $ (" # myLink "). unbind ("click. mySpecialClick "); AJAX 1. avoid using. getJson () and. get () is simple to use $. ajax (), because this is. get () Internal call. 2. Do not use http requests on https websites. Better use of a stateless url (remove HTTP or HTTPS from your URL ). 3. Do not send Request Parameters on URLs, and use data objects to send them. // Less readable... $. ajax ({url: "something. php? Param1 = test1 & param2 = test2 ",....}); // More readable... $. ajax ({url: "something. php ", data: {param1: test1, param2: test2}); 4. specify the ype as much as possible, so that you can easily know which type of data you want (see the following Ajax template example) 5. event proxy is used to bind events to content loaded using Ajax. Event proxy has advantages in asynchronous loading, it can process events from child element loaded into the document after a period of time. $ ("# Parent-container"). on ("click", "a", delegatedClickHandlerForAjax); 6. Use the Promise interface. More examples $. ajax ({...}). then (successHandler, failureHandler); // ORvar jqxhr = $. ajax ({...}); jqxhr. done (successHandler); jqxhr. fail (failureHandler); 7. ajax template example. More information var jqxhr =$. ajax ({url: url, type: "GET", // default is GET but you can use other verbs based on your needs. cache: true, // default is true, but false for dataType 'script' and 'jsonp', so set it on need basis. data: {}, // add your request parameters in the data object. dataType: "json", // specify the dataType for future reference jsonp: "callback", // only specify this to match the name Of callback parameter your API is expecting for JSONP requests. statusCode: {// if you want to handle specific error codes, use the status code mapping settings. 404: handler404, 500: handler500}); jqxhr. done (successHandler); jqxhr. fail (failureHandler); effect and Animation 1. the animation function is implemented in a consistent way. 2. Do not overdo the animation effect to meet the needs of the user experience. Try to use simple show/hide, toggle and slideUp/slideDown to show and hide an element. Use preset values to set the animation speed 'fast ', 'slow', or 400 (medium) Plug-in 1. always select a plug-in with good support, improved documentation, fully tested and active community. 2. Check whether the plug-in is compatible with the current jQuery version. 3. Some common functions should be written as jQuery plug-ins. JQuery plug-in template example chain Syntax 1. Use the chain syntax as an alternative to variable caching and multiple selector calls. $ ("# MyDiv "). addClass ("error "). show (); 2. when you call more than three chain calls or the event designation becomes complicated, use line breaks and appropriate indentation to improve code readability. $ ("# MyLink "). addClass ("bold "). on ("click", myClickHandler ). on ("mouseover", myMouseOverHandler ). show (); 3. for very long chain calls, it is best to use variables to save intermediate results to simplify code miscellaneous. $ myLink. attr ("href ","#"). attr ("title", "my link "). attr ("rel", "external"); // BAD, 3 callto attr () // GOOD, only 1 call to attr () $ myLink. attr ({href: "#", title: "my link", rel: "external"}); 2. do not mix CSS with jQuery. $ ("# Mydiv" ).css ({'color': red, 'font-weight ': 'bold '});. error {color: red; font-weight: bold;}/* GOOD */$ ("# mydiv "). addClass ("error"); // GOOD3. do not use discarded methods. It is important to avoid using them in every new version. Here is a list of discarded methods. 4. Merge the native javascript code and jQuery code if necessary. Let's take a look at the performance comparison. $ ("# MyId"); // is still little slower than...doc ument. getElementById ("myId ");

Related Article

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.