jquery--[Coding specifications and best practices]

Source: Internet
Author: User

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
    • 1. All variables that use or cache jquery objects should $ begin with.

    • 2. Always cache the objects returned by the jquery selector in a local variable for reuse.

var $myDiv = $ ("#myDiv"); $myDiv. Click (function () {...});

    • 3, use the peak camel type named variable.

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 ");

    • 3. Use the method in the ID > sub-node level selector find() . Because the first half of the selector does not use the Sizzle selector engine to find the element.

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 ");

    • 4. The second half of the selector is clearer than the first part.

Not optimized $ ("Div.data. Gonzalez");//optimize $ (". Data Td.gonzalez");

    • 5, avoid redundant selectors.

$ (". Data table.attendees Td.gonzalez");//Better: If necessary, remove the intermediate unnecessary content $ (". Data Td.gonzalez");

    • 6. Add the context to the selector.

To scan the entire DOM tree looking for $ ('. class ');//Only Scan $ ('. Class ', ' #class-container ') in #class-container;

    • 7. Avoid using a wildcard selector.

$ (' div.container > * '); bad$ (' Div.container '). Children (); BETTER

    • 8. Avoid using an implicit wildcard selector. When the following input is omitted, a wildcard selector is implicitly used.

$ (' Div.someclass:radio '); bad$ (' Div.someclass input:radio '); Good

    • 9, the ID selector is used document.getElementById() , the ID selector does not require a nested ID.

$ (' #outer #inner '); bad$ (' Div#inner '); bad$ ('. Outer-container #inner '); bad$ (' #inner '); Good

DOM Operations
    • 1. Always detach existing DOM elements and then attach them into the DOM.

var $myList = $ ("#list-container > Ul"). Detach ();//... Many DOM manipulation $mylist.appendto ("#list-container") for $mylist;

    • 2. Use a string connection or array.join () instead of the. Append () method.

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 ("));

    • 3, do not manipulate unknown elements.

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);

    • 3. The Document ready function should not be an anonymous function. Anonymous functions cannot be reused or tested against them.

$ (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>

    • 5, do not add the behavior in the HTML file (inline JS), this is the nightmare of debugging. It is easy to unbind events after always using jquery binding events.

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

    • 6. Use a custom namespace for events, if necessary. This helps to unbind a particular event on a DOM element without affecting other events on that DOM element.

$ ("#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&param2=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);

    • 6. Using Promise

$.ajax ({...}). Then (Successhandler, Failurehandler);//ORvar JQXHR = $.ajax ({...}); Jqxhr.done (Successhandler); Jqxhr.fail (Failurehandler);

    • 7. Ajax Template Code:

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
    • 1, try to use chained notation instead of using variable caching or calling selector methods multiple times.

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

    • 2. Use line breaks and indents to preserve code readability when chained more than three times or because event bindings become complex.

$ ("#myLink"). AddClass ("bold"). On ("click", Myclickhandler). On ("MouseOver", Mymouseoverhandler). Show ();

    • 3. For longer chained calls, it is acceptable to cache an intermediate object with a variable.

Other principles
    • 1, the parameters to use the object literal.

$myLink. attr ("href", "#"). attr ("title", "My Link"). attr ("rel", "external"); bad//good$mylist.attr ({href: "#", Title: "My Link", rel: "external"});

    • 2. Don't put CSS into jquery

$ ("#mydiv"). css ({' Color ': red, ' font-weight ': ' Bold '}); bad.error {color:red; font-weight:bold;}/* Good */$ ("#mydiv"). AddClass ("error"); Good

    • 3, do not use the method of abandonment.

    • 4. The native JS method can be used when needed.

$ ("#myId"); Or slow down some document.getElementById ("myId");

Article Source: http://www.w3cschool.cc

jquery--[Coding specifications and best practices]

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.