Best Practices for jquery programming

Source: Internet
Author: User
Tags anonymous bind mixed jquery cdn advantage

Load jquery

1. Adhere to the use of CDN to load jquery, the other server for free to help you hosting files cheap why not accounted for it. Click here to view the benefits of using CDN, and click here to view some of the mainstream jquery CDN addresses.

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 IE678 please use the 2.x version

The latest version of jquery is highly recommended for a handful of lucky few who don't consider compatibility

When you load jquery from a CDN server, it's best to write a full version (such as 1.11.0 instead of 1.11 or write a 1 directly)

Never repeat the load.

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 United States 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: On the fur does not detect the browser

About variables

It is best to add a $ prefix to a variable of type 1.jQuery.

2. Always deposit the content returned by the jquery selector into the variable for reuse

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

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

3. Using the Hump name

About selectors

1. ID selector as far 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 see this performance comparison

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

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

3.ID Father container to find the child element below, use the. Found () method. The reason for doing this quickly is that selecting an element by ID does not use the sizzle engine. See here for details

4. Multi-level search, the right to specify as much detail as possible 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 comparisons

$ (". Data table.attendees Td.gonzalez");

Good way: Remove the redundancy in the middle

$ (". Data Td.gonzalez");

6. Specifies the context of the selection.

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

$ ('. class ');

The High-quality code: Because you only need to find within the specified container scope

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

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

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

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

8. Beware of the implicit universal selector. In fact, the use of the omitted is the * number wildcard. More information

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

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

9.ID has been shown to be unique, the back is using document.getElementById (), so the table is mixed with other selectors.

$ (' #outer #inner '); Dirty

$ (' Div#inner '); Mess

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

$ (' #inner '); Cleanly, the backstage only needs to call document.getElementById ()

DOM Operations related

1. The operation of any element before the uninstall from the document, and then paste back. It's a little bit 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 then pasted into the DOM at a one-time. Specifically, performance comparisons

It's not good.

var $myList = $ ("#list");

for (var i = 0; i < 10000; i++) {

$myList. Append ("

    • "+i+"

");

}

That's good.

var $myList = $ ("#list");

var list = "";

for (var i = 0; i < 10000; i++) {

List = "

    • "+i+"

";

}

$myList. HTML (list);

But it's better.

var array = [];

for (var i = 0; i < 10000; i++) {

Array[i] = "

    • "+i+"

";

}

$myList. HTML (Array.join ('));

3. Do not deal with elements that do not exist. Details

Unscrupulous approach: The jquery background to run after three functions will know that this element does not actually exist

$ ("#nosuchthing"). Slideup ();

It should be.

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.

$ ("#myLink"). On ("click", Function () {...}); Table like this

Such

function Mylinkclickhandler () {...}

$ ("#myLink"). On ("click", Mylinkclickhandler);

3. Callback for handling document ready events also uses anonymous functions, which are not easily debugged for maintenance testing and reuse: (

$ (function () {...}); Bad practice: Cannot take advantage of this function and write test cases for it

Good practice.

$ (initpage); or $ (document). Ready (Initpage);

function Initpage () {

Here you can initialize the program.

}

4. Further, it is a good idea to put the handlers for the ready event into a page in an external file, and the code embedded in the page can only be invoked.

5. Tens of millions of tables to write inline to the HTML of the JS code, this is the nightmare of debugging! You should always use jquery to bind events with your programs, so that you can easily unbind them dynamically at any time.

My link

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

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

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 the jquery is still converting it to the former

2. The table uses HTTP to initiate the request to the HTTPS site, preferably simply by specifying the table (removing HTTP or https from your URL)

3. Table in the link inside the embedded parameters, please use a special parameter settings to pass

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 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 know more.

$ ("#parent-container"). On ("Click", "a", delegatedclickhandlerforajax);

6. Use the Promise mode. More examples

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

Or

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

Jqxhr.done (Successhandler);

Jqxhr.fail (Failurehandler);

7. One point of standard Ajax template. Search for the root cause

var jqxhr = $.ajax ({

Url:url,

Type: ' Get ',//The default is ' take ', you can change it as needed

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

Data: {},//Put the request parameter here.

DataType: "JSON",//specifying the type of data you want

JSONP: "Callback",//Specify callback handling request for JSONP type

StatusCode: {//If you want to deal with all the wrong states

404:handler404,

500:handler500

}

});

Jqxhr.done (Successhandler);

Jqxhr.fail (Failurehandler);

Animation and special effects

1. Maintain a consistent style of unified animation implementation

2. User experience, table abuse animation effects

Show elements by using simple display hiding, state switching, sliding into slide out, etc.

Use preset values to set the speed of the animation ' fast ', ' slow ', or 400 (medium speed)

Plug-in related

1. Always choose a plug-in with good support, perfect documentation, comprehensive testing and community active

2. Note whether the plug-in used is compatible with the currently used jquery version

3. Some common functions should be written as jquery plug-ins. Write template for a jquery plug-in

Chain syntax

1. In addition to saving the results returned by the jquery selector with a variable, you can also use a good chained call.

$ ("#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 a newline and appropriate indentation.

$ ("#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 arguments

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

Yes, only one attr was called.

$myLink. attr ({

HREF: "#",

Title: "My Link",

Rel: "External"

});

2. The table will be CSS and jquery mixed

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

. Error {/* good * *

color:red;

Font-weight:bold;

}

$ ("#mydiv"). AddClass ("error");

3. Always pay attention to the official changelog, the table uses the method which abandons. 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");

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.