Detailed explanation of jquery advanced programming Best Practices

Source: Internet
Author: User
Tags jquery cdn

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.
Copy codeThe Code is as follows:
<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.
Copy codeThe Code is as follows:
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.
Copy codeThe Code is as follows:
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
Copy codeThe Code is as follows:
// Ugly
$ ("Div. data. gonzarez ");
// After Optimization
$ (". Data td. gonzarez ");

5. Avoid redundancy. For details or view Performance Comparison
Copy codeThe Code is as follows:
$ (". Data table. attendees td. gonzarez ");

// Good method: Remove intermediate Redundancy
$ (". Data td. gonzarez ");

6. Specify the selected context.
Copy codeThe Code is as follows:
// Poor code: You need to traverse the entire DOM to find the. class
$ ('. Class ');
// High-performance code: Because you only need to search within the specified container range
$ ('. Class',' # class-iner ');

7. Use a universal selector for tables. View Details
Copy codeThe Code is as follows:
$ ('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
Copy codeThe Code is as follows:
$ ('Div. someclass: radio '); // difference
$ ('Div. someclass input: radio '); // stick

9. ID indicates that the table is unique, and document. getElementById () is used.
Copy codeThe Code is as follows:
$ ('# Outer # inner'); // dirty
$ ('Div # inner '); // messy
$ ('. Outer-container # inner'); // difference
$ ('# Inner'); // clean, 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.
Copy codeThe Code is as follows:
Var $ myList = $ ("# list-container> ul"). detach ();
// A lot of processing for $ myList
$ 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> ");
}

// This is good
Var $ myList = $ ("# list ");
Var list = "";
For (var I = 0; I <10000; I ++ ){
List + = "<li>" + I + "</li> ";
}
Using mylist.html (list );

// But this is better
Var array = [];
For (var I = 0; I <10000; I ++ ){
Array [I] = "<li>" + I + "</li> ";
}
Using mylist.html (array. join (''));

3. Do not process nonexistent elements. Details
Copy codeThe Code is as follows:
// Bad practice: jQuery does not actually exist after running three functions in the background.
$ ("# Nosuchthing"). slideUp ();
// This should be the case
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.
Copy codeThe Code is as follows:
$ ("# 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 :(
Copy codeThe Code is as follows:
$ (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, preferably
The ready event handler is also put into an external file and introduced to the page, while the embedded code in the page only needs to be called.
Copy codeThe Code is as follows:
<Script src = "my-document-ready.js"> </script>
<Script>
// Start with 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.
Copy codeThe Code is as follows:
<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.
Copy codeThe Code is as follows:
$ ("# MyLink"). on ("click. mySpecialClick", myEventHandler); // good
// Then, 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
Copy codeThe Code is as follows:
// 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
Copy codeThe Code is as follows:
$ ("# Parent-container"). on ("click", "a", delegatedClickHandlerForAjax );

6. Use Promise mode. More examples
Copy codeThe Code is as follows:
$. Ajax ({...}). then (successHandler, failureHandler );

// Or
Var jqxhr = $. ajax ({...});
Jqxhr. done (successHandler );
Jqxhr. fail (failureHandler );

7. Standard Ajax templates. Root Cause
Copy codeThe Code is as follows:
Var jqxhr = $. ajax ({
Url: url,
Type: "GET", // The default value is GET. You can change the value as needed.
Cache: true, // The default value is true. However, for scripts, the jsonp type is false. You can set this parameter on your own.
Data: {}, // put the request parameters here.
DataType: "json", // specify the desired data type
Jsonp: "callback", // specifies the callback to process JSONP-type requests.
StatusCode: {// If You Want To handle errors in different 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.
Copy codeThe Code is as follows:
$ ("# 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.
Copy codeThe Code is as follows:
$ ("# 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
Copy codeThe Code is as follows:
$ MyLink. attr ("href ","#"). attr ("title", "my link "). attr ("rel", "external"); // bad: attr is called three times.
// Yes, it only calls attr once
$ MyLink. attr ({
Href :"#",
Title: "my link ",
Rel: "external"
});

2. the CSS and jQuery parameters are mixed in the table.
Copy codeThe Code is as follows:
$ ("# 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.

4. Use native JavaScript in a timely manner.
Copy codeThe Code is as follows:
$ ("# MyId"); // The number will still be inferior...

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.