Here are the basic specifications and best practices for writing jquery code, which do not include native JS specifications and best practices.
Load jquery
1, try to use CDN to load jquery.
<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 >
Baidu Public CDN Library in all regions of the country speed should be the fastest, JS library is also a lot, recommend everyone to use.
<script src= "Http://libs.baidu.com/jquery/1.8.3/jquery.min.js" ></script>
Also Pat Cloud JS Library Accelerator service in the domestic speed is also good, unfortunately JS cubby less.
<script src= "Http://upcdn.b0.upaiyun.com/libs/jquery/jquery-1.8.3.min.js" ></script>
Sina Js/css Library also known as Sina SAE Public Library, the speed of access in the country is also good, JS Library is also very full, recommend everyone to use.
<script src= "Http://lib.sinaapp.com/js/jquery/1.8.3/jquery.min.js" ></script>
jquery variables
var $myDiv = $ ("#myDiv"); $myDiv. Click (function () {...});
Selector Selector
1. When the ID selector is available, it uses the ID selection, which is used internally document.getElementById()
.
2. When using the class/pseudo class selector, always attach the element type to the selector to avoid scanning the entire DOM tree.
Bad scans the entire DOM tree for the "Products" class name var $products = $ (". Products");//Good only scans the DIV element for the "the" "Items" class name var $products = $ (" Div.products ");
Bad, the sizzle selector engine looks for the hierarchy var $productIds = $ ("#products div.id");//good, only div.id walk sizzle selector engine var $productIds = $ ("#product S "). Find (" div.id ");
Not optimized $ ("Div.data. Gonzalez");//optimize $ (". Data Td.gonzalez");
$ (". Data table.attendees Td.gonzalez");//Better: If necessary, remove the intermediate unnecessary content $ (". Data Td.gonzalez");
To scan the entire DOM tree looking for $ ('. class ');//Only Scan $ ('. Class ', ' #class-container ') in #class-container;
$ (' div.container > * '); bad$ (' Div.container '). Children (); BETTER
$ (' Div.someclass:radio '); bad$ (' Div.someclass input:radio '); Good
$ (' #outer #inner '); bad$ (' Div#inner '); bad$ ('. Outer-container #inner '); bad$ (' #inner '); Good
DOM Operations
var $myList = $ ("#list-container > Ul"). Detach ();//... Many DOM manipulation $mylist.appendto ("#list-container") for $mylist;
Badvar $myList = $ ("#list"); for (var i = 0; i < 10000; i++) {$myList. Append ("<li>" +i+ "</li>");} Goodvar $myList = $ ("#list"); var list = ""; for (var i = 0; I < 10000; i++) {list + = "<li>" +i+ "</li>";} $myList. HTML (list);//even fastervar array = []; for (var i = 0; i < 10000; i++) {Array[i] = "<li>" +i+ "</li>";} $myList. HTML (Array.join ("));
Bad: In order to perform 3 functions inside this function, it is found that the selector may have an empty content of $ ("#nosuchthing"). Slideup ();//Goodvar $mySelection = $ ("#nosuchthing"); if ($ Myselection.length) {$mySelection. Slideup ();}
Event
1. Use only one document ready function per page. Facilitates commissioning.
2. Do not use anonymous functions to bind events. Anonymous functions are not conducive to debugging, maintenance, testing, and reuse.
$ ("#myLink"). On ("click", Function () {...}); bad//goodfunction Mylinkclickhandler () {...} $ ("#myLink"). On ("click", Mylinkclickhandler);
$ (function () {..}); Bad: Not easy to reuse also not conducive to testing//good$ (initpage); or $ (document). Ready (initpage); function Initpage () {///document can initialize variables and invoke other initialization functions}
4, the document ready function should be placed in an external file, after other initialization settings, in line JS call these functions.
<script src= "My-document-ready.js" ></script><script>//any other global variable (document) that needs to be set. Ready (Initpage ); or $ (initpage);</script>
<a id= "MyLink" href= "#" onclick= "MyEventHandler ();" >my link</a> <!--bad-->$ ("#myLink"). On ("click", MyEventHandler); Good
$ ("#myLink"). On ("Click.myspecialclick", MyEventHandler); good//will be easy to unbind this specific click event $ ("#myLink"). Unbind ("Click.myspecialclick");
Ajax
1, avoid the use .getJSON()
and .get()
, only use $.ajax()
, the former two are in the internal use of the latter.
2. Do not https
use the request on the website http
. Focus on the modeless URL (remove Http/https on the URL).
3, do not put the request parameters in the URL, but placed in the data object.
Unreadable $.ajax ({url: "Something.php?param1=test1¶m2=test2", ...}); /readable $.ajax ({url: "something.php", data: {Param1:test1, Param2:test2}});
4. Explicitly set the type of data dataType
, so it is easy to know what data is currently being processed.
5. Use event proxies whenever possible to bind events to an AJAX-loaded DOM element. The advantage of event proxies is that the elements that Ajax later add to the DOM can also respond to events.
$ ("#parent-container"). On ("Click", "a", delegatedclickhandlerforajax);
$.ajax ({...}). Then (Successhandler, Failurehandler);//ORvar JQXHR = $.ajax ({...}); Jqxhr.done (Successhandler); Jqxhr.fail (Failurehandler);
var jqxhr = $.ajax ({url:url, type: "Get",//default get, configurable cache:true as required,//default value True, DataType is ' script ' or ' JSO ' NP ' is false, can be configured as required data: {},//Request Parameter Object DataType: "JSON",//Set data type JSONP: "Callback",//Set this item only when Operation Jsonp STATUSC Ode: {//callback handler for specific error code 404:handler404, 500:handler500}}); Jqxhr.done (Successhandler); Jqxhr.fail (Failurehand LER);
Effects and animations
1, adopt the Unified animation realization Way.
2, do not overuse animation effects, unless the pursuit of user experience.
Try to use a simple Show/hide/toggle/slideup/slidedown method to display hidden elements.
Try to use a predefined animation interval: slow
, fast
or400
Plug - ins
1. Always choose plugins with good maintenance, excellent documentation, good testing and community support.
2. Carefully check the compatibility of the plugin with the jquery version being used.
3. Any generic component should be extracted as a jquery plugin.
Chained notation
$ ("#myDiv"). AddClass ("Error"). Show ();
$ ("#myLink"). AddClass ("bold"). On ("click", Myclickhandler). On ("MouseOver", Mymouseoverhandler). Show ();
Other principles
$myLink. attr ("href", "#"). attr ("title", "My Link"). attr ("rel", "external"); bad//good$mylist.attr ({href: "#", Title: "My Link", rel: "external"});
$ ("#mydiv"). css ({' Color ': red, ' font-weight ': ' Bold '}); bad.error {color:red; font-weight:bold;}/* Good */$ ("#mydiv"). AddClass ("error"); Good
$ ("#myId"); Or slow down some document.getElementById ("myId");
Article Source: http://www.w3cschool.cc
jquery--[Coding specifications and best practices]