Best Practices for jquery programming

Source: Internet
Author: User
Tags coding standards jquery cdn

Source: Public number "front-end Encyclopedia"

Links: http://dwz.cn/1Bhn6m

==========================

English: Abhinay Rathore

Translation: Liu Yongyong (@ Liu Yongyong)

Website: http://lab.abhinayrathore.com/jquery-standards/

It seems to be a feedly subscription to see the article, after reading it feels very good, translation of spare, more see benefit.

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 the $ symbol, so you use the knife symbol for JQuery code, and use ' jquery ' instead. and call $.noconflict () to ensure that no conflicts occur.

7. To detect whether the browser supports some new features, use Modernizr. In-stream advertising: On the non-detection of hair browser

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

var $products = $ ("div.products"); Slow

var $products = $ (". Products"); Fast

3. Use the Hump to name

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 $products = $ ("div.products"); Slow

var $products = $ (". Products"); Fast

3.ID Father container look for child elements below, please use 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");

After optimization

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

Poor code: Because you need to traverse the entire DOM to find the. class

$ ('. class ');

Code: Because you only need to find it within the specified container range

$ ('. Class ', ' #class-container ');

7. The table uses a universal selector. View specific explanations

$ (' div.container > * '); Poor

$ (' Div.container '). Children (); Great

8. Be wary of an implicit universal selector. In the case of ellipsis, the use of the * number wildcard is actually used. More information

$ (' Div.someclass:radio '); Poor

$ (' Div.someclass input:radio '); Great

The 9.ID is already unique, and the document.getElementById () is used behind it, so the table is mixed with the other selectors.

$ (' #outer #inner '); Dirty

$ (' Div#inner '); Disorderly

$ ('. Outer-container #inner '); Poor

$ (' #inner '); 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 whole bunch 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 (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>";

}

$myList. HTML (list);

But it's better.

var array = [];

for (var i = 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 will not know this element actually does not 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.

$ ("#myLink"). On ("click", Function () {...}); Table This way

Such

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: You can't 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, 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>

Initialize some of the necessary global variables

$ (document). Ready (Initpage); 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.

<a id= "MyLink" href= "#" onclick= "MyEventHandler ();" >my link</a> <!--bad---

$ ("#myLink"). On ("click", MyEventHandler); Good

6. If it is possible to use a namespace when binding an event handler, it is convenient to unbind without affecting other bindings.

$ ("#myLink"). On ("Click.myspecialclick", MyEventHandler); Not bad

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

URL: "Something.php?param1=test1&param2=test2",

....

});

Easier to read ...

$.ajax ({

URL: "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.

$.ajax ({...}). Then (Successhandler, Failurehandler);

Or

var jqxhr = $.ajax ({...});

Jqxhr.done (Successhandler);

Jqxhr.fail (Failurehandler);

7. Standard Ajax template one point. Chasing roots

var jqxhr = $.ajax ({

Url:url,

Type: "Get",//default is GET, you can change as needed

Cache:true,//default is True, but for Script,jsonp type false, you can set it yourself

Data: {},//The request parameter is placed here.

DataType: "JSON",//Specify the desired data type

JSONP: "Callback",//Specify callback to handle JSONP type of request

StatusCode: {//If you want to deal with errors in each state

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

$myLink. attr ("href", "#"). attr ("title", "My Link"). attr ("rel", "external"); Bad: called three times attr

Yes, only once attr is called.

$myLink. attr ({

HREF: "#",

Title: "My Link",

Rel: "External"

});

2. Table to blend CSS with jquery

$ ("#mydiv"). css ({' Color ': red, ' font-weight ': ' Bold '}); Not good

. Error {/* good */

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

$ ("#myId"); How much will be inferior to ...

document.getElementById ("MyId");

REFERENCE

Original: Coding Standards & Best Practices http://lab.abhinayrathore.com/jquery-standards/

The reference of the original

    • JQuery performance:http://learn.jquery.com/performance/

    • JQuery learn:http://learn.jquery.com

    • JQuery API docs:http://api.jquery.com/

    • JQuery Coding standards and best practice:http://www.jameswiseman.com/blog/2010/04/20/jquery-standards-and-best-practice/

    • JQuery Plugin boilerplate:http://stefangabos.ro/jquery/jquery-plugin-boilerplate-revisited/

Best Practices for jquery programming

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.