This article mainly introduces jquery Advanced programming Best Practice detailed explanation, the study JQ friend must need this, the reference under Bar
Load jquery 1. Insist on using a CDN to load jquery, which is why you don't take advantage of the cheap hosting files that someone else's server does for free. Click here to view the benefits of using CDN, and click here to view some of the mainstream jquery CDN addresses. Code 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 reasons, it is a good idea to provide a local backup so that the site can work when you cannot get jquery from a remote CDN server, as shown in the code above. See here for more details. 3. Use the URL of the bare protocol (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. Details here, or view a HTML5 page standard template. 5. Which version should be used? If you want to be compatible with IE678 please use the 2.x version for a handful of lucky few who do not consider compatibility, strongly recommend using the latest version of jquery when loading jquery from a CDN server, it's best to write a full version (such as 1.11.0 instead of 1.11 or write 1 directly) Do not 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 table again with the U.S. knife symbol for jQuery coding, and please use ' jquery ' instead. and call $.noconflict () to ensure that no conflicts occur. 7. To detect whether the browser supports some new features, please use MODERNIZR. Advertising spots: On the hair do not detect browsers variables with variable 1.jQuery types It is best to add a $ prefix. 2. Always store the contents of the jquery selector back into the variable for reuse code as follows: Var $produCTS = $ ("div.products"); Slow var $products = $ (". Products"); Quick 3. Use the Hump naming about selector 1. ID selector as much as possible. The underlying mechanism is actually invoking the native document.getElementById (), so the speed is faster than other selectors. 2. The table specifies the type of the element when using the class selector. I don't believe you. The performance comparison code is as follows: var $products = $ ("div.products"); Slow var $products = $ (". Products"); Quick 3.ID father container to find child elements below please use the. Found () method. The reason for doing this quickly is that selecting an element by ID does not use the sizzle engine. For more information see here 4. Multi-level lookup, the right to specify as much detail as possible and the left is as simple as possible. Learn more code as follows://Ugly $ ("Div.data. Gonzalez"); After optimization $ (". Data Td.gonzalez"); 5. Avoid redundancy. Details or view performance comparison code as follows: $ (". Data table.attendees Td.gonzalez"); //Good way: Remove the middle redundancy $ (". Data Td.gonzalez"); 6. Specifies the context of the selection. The code is as follows://Bad code: Because you need to traverse the entire DOM to find. Class $ ('. class '); The code of High-quality: Because you need to look up $ ('. Class ', ' #class-container ') within the scope of the specified container; 7. The table uses a universal selector. View the specific interpretation code as follows: $ (' div.container > * '); Difference $ (' Div.container '). Children (); Bar 8. Beware of implicit universal selector. In fact, the use of the omitted is the * number wildcard. More information codes are as follows: $ (' Div.someclass:radio '); Difference $ (' dIv.someclass Input:radio '); The bar 9.ID has been shown to be unique, with document.getElementById () behind it, so the table is mixed with other selectors. Code as follows: $ (' #outer #inner '); Dirty $ (' div#inner '); Disorder $ ('. Outer-container #inner '); Difference $ (' #inner '); Cleanly, the background simply calls document.getElementById () DOM operations related 1. Before you can manipulate any element, uninstall it from the document, and then post it back. It's going to be fine. code is as follows: var $myList = $ ("#list-container > Ul"). Detach (); //... A large pile of treatment of $mylist $myList. Appendto ("#list-container"); 2. In the code, the HTML is organized and then pasted into the DOM at a one-time. Specifically, performance comparisons //So bad var $myList = $ ("#list"); for (var i = 0; I < 10000 i++) { $myList. Append ("<li>" +i+ "</li>")} //So good var $myList = $ ("#list"); var list = ""; for (var i = 0; I < 10000 i++) { list = "<li>" +i+ "</li>";} $myList. html (list); /But this is better var array = []; for (var i = 0; i < 10000; i++) { array[i] = "<li>" +i+ "</li&" gt; "; } $myList. html (Array.join (')); 3. Do not deal with elements that do not exist. Details Codeas follows://unscrupulous practices: jquery background to run after three functions will know that this element does not exist in fact, $ ("#nosuchthing"). Slideup (); Should such var $mySelection = $ ("#nosuchthing"); if ($mySelection. length) { $mySelection. Slideup ();} Event-related 1. One page writes only one document ready event handler. This code is both clear and easy to debug, and easily track the process of the code. 2. The table uses an anonymous function to do the callback of the event. Anonymous functions are not easily debugged for maintenance testing and reuse. Maybe you want to take a look at this. code is as follows: $ ("#myLink"). On ("click", Function () {...}); Table so//This function Mylinkclickhandler () {...} $ ("#myLink"). On ("click", Mylinkclickhandler); 3. Callback for handling document ready events also uses anonymous functions, which are not easy to debug maintenance tests and multiplexing: ( Code is as follows: $ (function () {...}); Bad practice: Cannot take advantage of this function nor write test cases for it //good Practices $ (initpage); or $ (document). Ready (Initpage); function Initpage () { //Here you can initialize the program.} 4. Further, it is best to put the handlers for the ready event into the external file, and the code embedded in the page needs to be called. Code as follows: <script src= "My-document-ready.js" ></script> <script> //Initial by some necessary global variables $ ( Document). Ready (Initpage); or $ (initpage); </script> 5. Tens of millions of tables written inline to HTML JS code, this is the nightmare of debugging! should alwaysUse jquery to bind events with their own programs, which makes it easy to unbind dynamically at any time. Code as follows: <a id= "MyLink" href= "# onclick=" MyEventHandler (); " >my Link</a> <!--is not good--> $ ("#myLink"). On ("click", MyEventHandler); Good 6. If possible, use a namespace when binding event handlers, so that you can easily unbind without affecting other bindings. Code as follows: $ ("#myLink"). On ("Click.myspecialclick", MyEventHandler); Good//After that, let's gracefully unbind $ ("#myLink"). Unbind ("Click.myspecialclick"); Asynchronous operations 1. Use $.ajax () directly with the table to use the. Getjson () or. get (), because jquery is still converting it to the former 2. The table uses HTTP to initiate the request to the HTTPS site. It is best to specify the table (remove HTTP or https from your URL) 3. Table in the link inside the embedded parameters, please use the special parameter settings to pass the code as follows://difficult to read code ... $.ajax ({ URL: "Something.php?param1=test1¶m2=test2", ...}); //easier to read ... $.ajax ({ URL: "something.php", data: {param1:test1, Param2:test2}}); 4. Try to identify the data type so that you know exactly what kind of data to process (see the Ajax template mentioned below) 5. For asynchronous dynamically loaded content, it is best to use proxies to bind event handlers. The advantage is that it is also valid for element events that are dynamically loaded later. You might want to learn more code as follows: $ ("#parent-container"). On ("Click", "a", DELEGATEDCLIckhandlerforajax); 6. Use Promise mode. More examples codes are as follows: $.ajax ({...}). Then (Successhandler, Failurehandler); //or var jqxhr = $.ajax ({...}); Jqxhr.done (Successhandler); Jqxhr.fail (Failurehandler); 7. Standard Ajax template one point. Trace the source code as follows: var jqxhr = $.ajax ({ Url:url, type: "Get",//default is a, you can change the as needed   ; Cache:true,//default to True, but for Script,jsonp type false, you can set data: {},//Put the request parameter here. DataType: "JSON",//specifying desired data type JSONP: "Callback",//Specifying callback processing JSONP type of request StatusCode : {///If you want to deal with all state errors 404:handler404, 500:handler500 &NBS P } }); Jqxhr.done (Successhandler); Jqxhr.fail (Failurehandler); Animation and special effects 1. Maintain a consistent style of unified animation implementation 2. User experience, table misuse of animation effect Use concise display hidden, state switch, slide into slide out and so on to show the elements Use preset values to set the speed of the animation ' fast ', ' slow ', or 400 (medium speed) plug-in related 1. Always choose a plugin with good support, perfect documentation, fully tested and community active 2. Note whether the plug-in used with the current jquery version is alsoCapacity 3. Some common functions should be written as jquery plug-ins. One point jquery plugin writing template chain syntax 1. In addition to saving the results returned by the jquery selector with a variable, you can also make good use of chained calls. Code as follows: $ ("#myDiv"). AddClass ("Error"). Show (); 2. When the chained call is more than 3 times or the code is slightly more complex due to a binding callback, the readability of the code is improved by using line wrapping and appropriate indentation. Code as follows: $ ("#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 results with a variable. other 1. Use object literals to pass parameters code is as follows: $myLink. attr ("href", "#"). attr ("title", "My Link"). attr ("rel", " external "); Bad: called three times attr//Yes, only one call attr $myLink. attr ({ href: "#", title: "My Link", rel : "External"}); 2. Table will CSS and jquery miscellaneous Code as follows: $ ("#mydiv"). css ({' Color ': red, ' font-weight ': ' Bold '}); Bad. Error {/* good * * color:red Font-weight:bold} $ ("#mydiv"). AddClass ("error"); & nbsp 3. Always pay attention to the official changelog, the table use abandoned method. 4. Timely use of native JAVAscript. Code as follows: $ ("#myId"); How much will be inferior to ...