JQuery programming best practices and jquery Best Practices

Source: Internet
Author: User
Tags coding standards jquery cdn

JQuery programming best practices and jquery Best Practices

Source: Public Account [frontend overview]

Link: http://dwz.cn/1Bhn6m

======================================

English: Abhinay Rathore

Translation: Liu wayong (@ Liu wayong)

Web: http://lab.abhinayrathore.com/jquery-standards/

======================================

It seems that the articles in feedly subscription are very good. After reading the articles, I think it is very good.

Load jQuery

1. Stick to using CDN to load jQuery. Why is it cheaper for someone else's server to help you host files for free. Click here to view the benefits of using CDN. Click here to view some mainstream jQuery CDN addresses.

<script type="text/javascript" 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" type="text/javascript"><\/script>')</script> 

2. For security, it is best to provide a local backup so that the website can work when jQuery cannot be obtained from a remote CDN server, as shown in the code above. For details, see this.

3. Use a bare URL (that is, remove http: or https :), as shown in the code above.

4. If possible, try to put your JavaScript and jQuery code at the bottom of the page. For more information, see here or view a standard HTML5 page template.

5. Which version is used?

  • If you want to be compatible with IE678, use the 2.x version.

  • We strongly recommend that you use the latest version of jQuery for a few lucky winners who do not need to consider compatibility.

  • When loading jQuery from the CDN server, it is best to write all the versions (for example, 1.11.0 instead of 1.11 or directly write 1)

  • Load tens of millions of records repeatedly

6. if you also use other JS frameworks such as Prototype, MooTools, and Zepto cloud, because they also use the $ symbol, you can use the $ symbol to encode the table with jQuery, use 'jquery 'instead. And call $. noConflict () to ensure that no conflict exists.

7. to check whether the browser supports some new features, use Modernizr. Insert advertisement

About Variables

1. A $ prefix is recommended for jQuery-type variables.

2. The content returned by the jQuery selector is often stored in variables for reuse.

Var $ products = $ ("div. products"); // slow var $ products = $ (". products"); // fast

3. Use the camper name

About Selector

1. ID selector as much as possible. The mechanism behind it is actually to call the native document. getElementById (), so the speed is faster than other selectors.

2. When the class selector is used, the table specifies the element type. Believe it or not, check the performance comparison.

Var $ products = $ ("div. products"); // slow var $ products = $ (". products"); // fast

3. Use the. find () method to search for child elements under the ID parent container. The reason for this is that the Sizzle engine is not used for element selection through id. For details, see here

4. In multi-level search, specify the vertices on the right as much as possible, while on the left as much as possible. Learn more

// Ugly $ ("div. data. gonzarez"); // After optimization $ (". data td. gonzarez ");

5. Avoid redundancy. For details or view Performance Comparison

$ (". Data table. attendees td. gonzarez"); // a good way: Remove intermediate redundancy $ (". data td. gonzarez ");

6. Specify the selected context.

// Poor code: You need to traverse the entire DOM to find the code. class $ ('. class ') // high-end code: Because you only need to search for $ ('. class ',' # class-iner ');

7. Use a universal selector for tables. View Details

$ ('Div. container> * '); // Difference $ ('div. iner'). children (); // great

8. Be cautious about Implicit universal selector. If this parameter is omitted, the wildcard * is used. More information

$ ('Div. someclass: radio '); // Difference $ ('div. someclass input: radio'); // great

9. ID indicates that the table is unique, and document. getElementById () is used.

$ ('# Outer # inner'); // dirty $ ('div # inner '); // random $ ('. outer-container # inner '); // Difference $ (' # inner '); // The background only needs to call document. getElementById ()

DOM operations

1. unmount any element from the document before operating it, and paste it back. You can also elaborate on this.

Var $ myList = $ ("# list-container> ul "). detach ();//... A lot of processing $ myList. appendTo ("# list-container ");

2. Organize the HTML in the Code and paste it to the DOM at one time. Specifically, Performance Comparison

// This is not good var $ myList = $ ("# list"); for (var I = 0; I <10000; I ++) {$ myList. append ("<li>" + I + "</li>");} // var $ myList = $ ("# list "); var list = ""; for (var I = 0; I <10000; I ++) {list + = "<li>" + I + "</li>" too many tables mylist.html (list); // But var array = []; for (var I = 0; I <10000; I ++) {array [I] = "<li>" + I + "</li>" too many tables mylist.html (array. join (''));

3. Do not process nonexistent elements. Details

// Bad practice: jQuery does not exist until it finishes running three functions in the background ("# nosuchthing "). slideUp (); // var $ mySelection = $ ("# nosuchthing"); if ($ mySelection. length) {$ mySelection. slideUp ();}

Event-related

1. Write only one ready event handler for the document on one page. In this way, the code is both clear and easy to debug and trace the code process.

2. The table uses anonymous functions for Event Callback. Anonymous functions are not easy to debug, maintain, test, and reuse. Maybe you want to be honest. Check it out.

$ ("# MyLink "). on ("click", function (){...}); // table like this // function myLinkClickHandler (){...} $ ("# myLink "). on ("click", myLinkClickHandler );

3. The callback for processing the ready event in the document also uses anonymous functions. Anonymous functions are not easy to debug, maintain, test, and reuse :(

$ (Function (){...}); // bad practice: you cannot use this function or write test cases for it. // good practice $ (initPage); // or $ (document ). ready (initPage); function initPage () {// here you can initialize the program}

4. Further, it is best to put the ready event handler into an external file and introduce it to the page, while the embedded code in the page only needs to be called.

<Script src = "my-document-ready.js"> </script> <script> // initialize some necessary global variables $ (document ). ready (initPage); // or $ (initPage); </script>

5. Tens of millions of tables write JS Code inline into HTML, which is a nightmare of debugging! JQuery should always be used to bind the built-in program of the event, so that the binding can be canceled dynamically at any time.

<A id = "myLink" href = "#" onclick = "myEventHandler ();"> my link </a> <! -- Not GOOD --> $ ("# myLink"). on ("click", myEventHandler);/GOOD

6. If you try to use a namespace when binding the event handler, you can easily unbind it without affecting other bindings.

$ ("# MyLink "). on ("click. mySpecialClick ", myEventHandler); // nice // later, let's unbind it elegantly $ (" # myLink "). unbind ("click. mySpecialClick ");

Asynchronous Operation

1. directly use $. ajax () and the table uses. getJson () or. get (), because jQuery still converts it into the former.

2. The table uses HTTP to initiate a request to the HTTPS site. It is best to simply specify the table (remove HTTP or HTTPS from your URL)

3. Insert parameters in the table link. use special parameter settings to pass

// Code that is not easy to read... $. ajax ({url: "something. php? Param1 = test1 & param2 = test2 ",....}); // easier to read... $. ajax ({url: "something. php ", data: {param1: test1, param2: test2 }});

4. Specify the data type as much as possible so that you can understand the data to be processed (see the Ajax template mentioned below)

5. For Asynchronous dynamic loading content, it is best to use a proxy to bind the event handler. This is also effective for element events that are dynamically loaded later. You may want to know more

$("#parent-container").on("click", "a", delegatedClickHandlerForAjax);

6. Use Promise mode.

$. Ajax ({...}). then (successHandler, failureHandler); // or var jqxhr = $. ajax ({...}); jqxhr. done (successHandler); jqxhr. fail (failureHandler );

7. Standard Ajax templates. Root Cause

 

Var jqxhr = $. ajax ({url: url, type: "GET", // The default value is GET. You can change cache: true as needed, // The default value is true, but for scripts, the jsonp type is false. You can set data :{}, // put the request parameters here. dataType: "json", // specify the desired data type jsonp: "callback", // specify the statusCode of the jsonp type request for callback processing: {// If You Want To handle errors in various States, 404: handler404, 500: handler500}); jqxhr. done (successHandler); jqxhr. fail (failureHandler );

Animation and special effects 

1. Maintain a consistent style of animation implementation

2. strictly follow the user experience and abuse animation effects on tables

  • Display elements with simple display hiding, status switching, slide-in and out effects

  • Use a preset value to set the animation speed to 'fast ', 'low', or 400 (medium speed)

Plug-ins

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. Template for writing jQuery plug-ins

Chain syntax 

1. Besides saving the results returned by the jQuery selector using variables, you can also use the chain call.

$("#myDiv").addClass("error").show();

2. When the chain call is more than three times or the code is slightly complicated due to the binding callback, use line breaks and appropriate indentation to improve the readability of the Code.

$("#myLink").addClass("bold").on("click", myClickHandler).on("mouseover", myMouseOverHandler).show();

3. For calls that are particularly long, it is best to use variables to save intermediate results to simplify the code.

Others

1. Use the object literal to pass Parameters

$ MyLink. attr ("href ","#"). attr ("title", "my link "). attr ("rel", "external"); // bad: attr is called three times. // yes. attr $ myLink is called only once. attr ({href: "#", title: "my link", rel: "external "});

2. the CSS and jQuery parameters are mixed in the table.

$ ("# Mydiv" ).css ({'color': red, 'font-weight ': 'bold'}); // bad
. Error {/* GOOD */color: red; font-weight: bold ;}
$("#mydiv").addClass("error");

3. Keep an eye on the official Changelog and discard the table. Click here to view all discarded Methods

4. Use native JavaScript in a timely manner. Performance Comparison

$ ("# MyId"); // The number of elements that may be compromised. ..doc ument. getElementById ("myId ");

REFERENCE 

Coding Standards & Best Practices http://lab.abhinayrathore.com/jquery-standards/

Reference of the original article

  • JQuery Performance: http://learn.jquery.com/performance/

  • JQuery Learn: http://learn.jquery.com

  • JQuery API Docs: http://api.jquery.com/

  • JQuery Coding Standards and Best Practice: http://www.jameswiseman.com/blog/2010/04/20/jquery-standards-and-best-practice/

  • JQuery Plugin Boilerplate: http://stefangabos.ro/jquery/jquery-plugin-boilerplate-revisited/

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.