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 $
symbols, so you use the knife symbol to jQuery
encode the table, and please use ' jQuery ' instead. And the call guarantees that $.noConflict()
there will be no conflicts.
7. To detect whether the browser supports some new features, use Modernizr.
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
// Slow var // Fast
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 // Slow var // Fast
3.ID Father container look for child elements below, using 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 redundancy $ (". Data Td.gonzalez");
6. Specify the context of the selection.
// Bad code: Because you need to traverse the entire DOM to find the. Class$ ('. class '/// code: Because you only have to look within the scope of the specified container to find $ ('. class ', ' # Class-container ');
7. The table uses a universal selector. View specific explanations
// Poor // Stick
8. Be wary of an implicit universal selector. In the case of ellipsis, the use of the * number wildcard is actually used. More information
// Poor // Stick
The 9.ID has been unique and is used behind the document.getElementById()
table, so the tables are mixed with other selectors.
// Dirty // Disorderly // Poor // 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
//It's bad .var$myList = $ ("#list"); for(vari = 0; I < 10000; i++) {$myList. Append ("<li>" +i+ "</li>");} //this is good.var$myList = $ ("#list");varList = ""; for(vari = 0; I < 10000; i++) {List+ = "<li>" +i+ "</li>";} $myList. HTML (list); //but it's better .varArray = []; for(vari = 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 through three functions to know that this element does not actually exist at all ("#nosuchthing"). Slideup (); // it should be . 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.
function // Table This way // this 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 use this function or write test cases for it // Good Practice // 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> // initialization of some necessary global variables // 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.
// Good
6. If it is possible to use a namespace when binding an event handler, it is convenient to unbind without affecting other bindings.
// Good // after that, 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 ({ "Something.php?param1=test1¶m2=test2", // easier to read ...) $.ajax ({ "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
// or var jqxhr = $.ajax ({...}); Jqxhr.done (Successhandler); Jqxhr.fail (Failurehandler);
7. Standard Ajax template one point. Chasing roots
varJQXHR =$.ajax ({url:url, type:"GET",//The default is get, which you can change as neededCachetrue,//The default is true, but for Script,jsonp type false, you can set your ownData: {},//put the request parameter here.DataType: "JSON",//Specify the type of data you wantJSONP: "Callback",//to specify a callback to handle a JSONP type of requestStatusCode: {//if you want to deal with all the wrong states ,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
// bad: Called three times attr // Yes, only once attr is called. $myLink. attr ({ "#", "My link", "external"});
2. Table to blend CSS with jquery
// not good . Error {/**/ color:red; Font-weight:bold;} $ ("#mydiv"). AddClass ("error");
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
// how much will be inferior to ... document.getElementById ("MyId");
Transferred from: http://www.css88.com/archives/4836