Best Practices for jquery programming

Source: Internet
Author: User
Tags jquery cdn

It seems to be a feedly subscription to see the article, after reading it feels very good, translation of spare, more see benefit.

Load jquery

1. Insist on using a CDN to load jquery, and this kind of other people's servers for free to help you to host the files of the cheap why not accounted for. Click here to see some of the main jquery CDN addresses for the benefits of using a CDN.

<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 reasons, it is best to provide a local backup so that the site can work when jquery cannot be obtained from the remote CDN server, as shown in the code above. See here for details.

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

4. If possible, place your JavaScript and jquery code at the bottom of the page. Click here for details, or view a HTML5 page standard template.

5. Which version should I use?

    • If you want to be compatible with IE678 please use the 2.x version of the form
    • The latest version of jquery is highly recommended for a handful of lucky ones who do not consider compatibility
    • When loading jquery from a CDN server, it is best to write the version full (e.g. 1.11.0 instead of 1.11 or write 1 directly)
    • Never repeat loading

6. If you also use other JS frames such as prototype, MooTools, Zepto and so on, because they also use the $ symbol, so you use the knife symbol for JQuery code, and use ' jquery ' instead. and call $.noconflict () to ensure that no conflicts occur.

7. To detect whether the browser supports some new features, use Modernizr. In-stream advertising: On the non-detection of hair browser

About variables

A variable of type 1.jQuery is best to add a $ prefix.

2. Always store the content returned by the jquery selector in a variable for reuse

var $products = $ ("div.products"); Slow var $products = $ (". Products"); Fast

3. Use the Hump to name

About selectors

1. Try the ID selector. The mechanism behind it is actually called the native document.getElementById (), so the speed is faster than the other selectors.

2. When using the class selector, the table specifies the type of the element. Don't believe you see this performance comparison

var $products = $ ("div.products"); Slow var $products = $ (". Products"); Fast

3.ID Father container look for child elements below, please use the. Find () method. The reason for this is that selecting elements by ID does not use the sizzle engine. See here for details

4. Multi-level search, the right side as far as possible to specify the detailed point and the left is as simple as possible. Learn More

Ugly $ ("Div.data. Gonzalez");//Optimized after $ (". Data Td.gonzalez");

5. Avoid redundancy. Details or view performance comparison

$ (". Data table.attendees Td.gonzalez"); Good way: Remove the middle of the redundancy $ (". Data Td.gonzalez");

6. Specify the context of the selection.

Poor code: Because you need to traverse the entire DOM to find the. class$ ('. class ');//code: Because only within the specified container scope to find $ ('. Class ', ' #class-container ');

7. The table uses a universal selector. View specific explanations

$ (' div.container > * '); Difference $ (' Div.container '). Children (); Great

8. Be wary of an implicit universal selector. In the case of ellipsis, the use of the * number wildcard is actually used. More information

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

The 9.ID is already unique, and the document.getElementById () is used behind it, so the table is mixed with the other selectors.

$ (' #outer #inner '); Dirty $ (' div#inner '); Disorderly $ ('. Outer-container #inner '); Difference $ (' #inner '); Neat, backstage just call document.getElementById ()
DOM Operations related

1. Before operating any element, remove it from the document and post it back. This is going to be a little more detailed.

var $myList = $ ("#list-container > Ul"). Detach ();//... A lot of treatment for $mylist $mylist.appendto ("#list-container");

2. In the code, the HTML is organized and pasted into the DOM at once. Specifically, performance comparisons

This is not good for var $myList = $ ("#list"), for (var i = 0; i < 10000; i++) {    $myList. Append ("<li>" +i+ "</li>");}//This Kind of good var $myList = $ ("#list"); var list = ""; for (var i = 0; I < 10000; i++) {    list + = "<li>" +i+ "</li>";} $myList. HTML (list); But such a better var array = []; for (var i = 0; i < 10000; i++) {    Array[i] = "<li>" +i+ "</li>";} $myList. HTML (Array.join ("));

3. Do not dispose of elements that do not exist. Details

Unscrupulous practice: jquery backstage to run the three function to know that this element does not exist in fact no $ ("#nosuchthing"). Slideup ();//should be such that var $mySelection = $ ("#nosuchthing"); if ( $mySelection. Length) {    $mySelection. Slideup ();}
Event-related

1. One page only writes a handler for the ready event of the document. This way the code is both clear and easy to debug and keep track of the code process.

2. The table uses an anonymous function to do the callback for the event. Anonymous functions are not easy to debug and maintain test and reuse. Maybe you want to take a look at this.

$ ("#myLink"). On ("click", Function () {...}); Table this//such function Mylinkclickhandler () {...} $ ("#myLink"). On ("click", Mylinkclickhandler);

3. The callback to handle the document ready event is also table with anonymous functions, anonymous functions are not easy to debug maintenance testing and reuse: (

$ (function () {...}); Bad practice: Cannot take advantage of this function nor write test cases for IT//good Practice $ (initpage); or $ (document). Ready (initpage); function Initpage () {    //Here you can initialize the program}

4. Further, it is better to put the handler for the ready event into the external file, and the code embedded in the page 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 thousands of tables write inline to the HTML JS code, this is debugging nightmare! You should always use jquery to bind the event's own program, which makes it easy to unbind dynamically at any time.

<a id= "MyLink" href= "#" onclick= "MyEventHandler ();" >my link</a> <!--bad---
$ ("#myLink"). On ("click", MyEventHandler); Good

6. If it is possible to use a namespace when binding an event handler, it is convenient to unbind without affecting other bindings.

$ ("#myLink"). On ("Click.myspecialclick", MyEventHandler); Good//After, let's gracefully unbind $ ("#myLink"). Unbind ("Click.myspecialclick");
Asynchronous operation

1. Directly use $.ajax () and the table to use. Getjson () or. get (), because jquery internally or it is converted to the former

2. Table for HTTPS sites using HTTP to initiate requests, it is better to simply specify the table (HTTP or https removed from your URL)

3. The table is embedded in the link parameter, please use special parameter settings to pass

Hard to read code ... $.ajax ({    URL: "Something.php?param1=test1&param2=test2",    ...});//easier to read ... $.ajax ({    URL: "something.php",    data: {param1:test1, Param2:test2}});

4. Try to identify the data type so that you know what data to work with (see the Ajax template mentioned below)

5. For asynchronous dynamically loaded content, it is best to use a proxy to bind the event handlers. The benefit is that it is also valid for element events that are dynamically loaded afterwards. You might want to know more.

$ ("#parent-container"). On ("Click", "a", delegatedclickhandlerforajax);

6. Use the Promise mode. More examples

$.ajax ({...}). Then (Successhandler, Failurehandler); or var jqxhr = $.ajax ({...}); Jqxhr.done (Successhandler); Jqxhr.fail (Failurehandler);

7. Standard Ajax template one point. Chasing roots

var jqxhr = $.ajax ({    url:url,    type: "Get",//default is GET, you can change cache:true as needed,    //default is True, but for script, The JSONP type is false, you can set the    data yourself: {},//Put the request parameter here.    DataType: "JSON",//Specify the desired data type    JSONP: "Callback",//Specify the callback to handle the JSONP type of request    StatusCode: {//If you want to handle the error of each state        404: handler404,        500:handler500    }}); Jqxhr.done (Successhandler); Jqxhr.fail (Failurehandler);
Animations and effects

1. Maintain a consistent style and consistent animation implementation

2. User experience, watch abuse animation effect

    • Display elements with simple display hiding, state toggle, slide-out, etc.
    • Use preset values to set the speed of animation ' fast ', ' slow ', or 400 (medium speed)
Plugin-related

1. Always choose a plugin with good support, complete documentation, fully tested and community active

2. Note whether the plug-in is compatible with the currently used jquery version

3. Some common functions should be written in jquery plugins. A part of jquery plugin authoring template

Chained syntax

1. In addition to using variables to save the results returned by the jquery selector, you can also make good use of chained calls.

$ ("#myDiv"). AddClass ("Error"). Show ();

2. When the chain call is more than 3 times or the code is slightly more complex due to binding callbacks, 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 exceptionally long calls, it is best to simplify the code by saving the intermediate result with a variable.

Other

1. Using object literals to pass parameters

$myLink. attr ("href", "#"). attr ("title", "My Link"). attr ("rel", "external"); Bad: Called three times attr//good, only called once attr$mylink.attr ({    href: "#",    title: "My Link",    rel: "external"});

2. Table to blend CSS with jquery

$ ("#mydiv"). css ({' Color ': red, ' font-weight ': ' Bold '}); Not good
. Error {/* good */    color:red;    Font-weight:bold;}

3. Keep an eye on the official changelog and use the abandoned method. Click here to view all deprecated methods

4. Use native JavaScript in a timely manner. Some performance comparisons related to this

 $ ("#myId");//How much will be inferior to ... document.getElementById ("myId"); 

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.