Best Practices for jquery programming

Source: Internet
Author: User
Tags deprecated event listener


Loading JQuery

Always try-to-use-a CDN to include jQuery on your page.

<script type= "Text/javascript" src= "//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" ></ Script>
<script>window.jquery | | document.write (' <script src= "http://www.qixoo.qixoo.com/js/jquery-2.1.4.min.js" type= "Text/javascript" > <\/script> ') </script>

For a list of popular jQuery CDNs.
Implement a fallback to your locally hosted library of same version as shown above.
Use URL (leave Http:or https:out) as shown above.
If possible, keep all your JavaScript and jQuery includes at the bottom of your page. and a sample on.
What version to use?
Do not use JQuery version 2.x if your support Internet Explorer 6/7/8.
For new Web-apps, if-do-not has any plugin compatibility issue, it's highly recommended to use the latest jQuery vers Ion.
When loading jQuery from CDN's, always specify the complete version number of want to load (example:1.11.0 as opposed to 1.11 or just 1).
Do not load multiple jQuery versions.
Do not use.
If you is using other libraries like Prototype, MooTools, Zepto etc. that uses $ sign as well, try not to use $ for calli ng jquery functions and instead use jQuery simply. You can return control of $ back to the other library with a call to $.noconflict ().
For the browser feature detection, use.

JQuery Variables

All variables is used to Store/cache JQuery objects should has a name prefixed with a $.
Always caches your JQuery selector returned objects in variables for reuse.

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

Use for naming variables.

Selectors

Use ID selector whenever possible. It is the faster because they is handled using document.getElementById ().
When using class selectors, don't use the element type in your selector.

var $products = $ ("div.products"); SLOW
var $products = $ (". Products"); FAST

Use the find for id->child nested selectors. The. Find () approach is faster because the first selection is handled without going through the Sizzle selector engine.

Bad, a nested query for Sizzle selector engine
var $productIds = $ ("#products div.id");

Good, #products is already selected by document.getElementById () so only div.id needs to go through Sizzle selector Eng Ine
var $productIds = $ ("#products"). Find ("div.id");

Be specific on the right-hand side of your selector, and less specific on the left.

Unoptimized
$ ("Div.data Gonzalez");

Optimized
$ (". Data Td.gonzalez");

Avoid excessive specificity. ,

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

Better:drop the middle if possible.
$ (". Data Td.gonzalez");

Give your selectors a Context.

Slower because it has to traverse the whole DOM for. Class
$ ('. class ');

FASTER because now it is only looks under Class-container.
$ ('. Class ', ' #class-container ');

Avoid Universal Selectors.

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

Avoid implied Universal selectors. When you leave off the selector, the Universal selector (*) is still implied.

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

Don ' t descend multiple IDs or nest when the selecting an ID. Id-only selections is handled using document.getElementById () so don ' TS mix them with other selectors.

$ (' #outer #inner '); Bad
$ (' Div#inner '); Bad
$ ('. Outer-container #inner '); Bad
$ (' #inner '); Good, only calls document.getElementById ()

DOM manipulation

Always detach any existing element before manipulation and attach it back after manipulating it.

var $myList = $ ("#list-container > Ul"). Detach ();
... a lot of complicated things on $myList
$myList. AppendTo ("#list-container");

Use the string concatenation or array.join () over. Append ().
Performance comparison:

Bad
var $myList = $ ("#list");
for (var i = 0; i < 10000; i++) {
$myList. Append ("<li>" +i+ "</li>");
}

Good
var $myList = $ ("#list");
var list = "";
for (var i = 0; i < 10000; i++) {
List + = "<li>" +i+ "</li>";
}
$myList. HTML (list);

Even FASTER
var array = [];
for (var i = 0; i < 10000; i++) {
Array[i] = "<li>" +i+ "</li>";
}
$myList. HTML (Array.join ("));

Don ' t Act on Absent Elements.

Bad:this runs three functions before it realizes there ' s nothing in the selection
$ ("#nosuchthing"). Slideup ();

Good
var $mySelection = $ ("#nosuchthing");
if ($mySelection. length) {
$mySelection. Slideup ();
}

Events

Use the one Document ready handler per page. It makes it easier to debug and keep track of the behavior flow.
Anonymous functions to attach events. Anonymous functions is difficult to debug, maintain, test, or reuse.

$ ("#myLink"). On ("click", Function () {...}); Bad

Good
function Mylinkclickhandler () {...}
$ ("#myLink"). On ("click", Mylinkclickhandler);

Document Ready event handler should is an anonymous function. Once again, anonymous functions is difficult to debug, maintain, test, or reuse.

$ (function () {...}); Bad:you can never reuse or write a test for this function.

Good
$ (initpage); or $ (document). Ready (Initpage);
function Initpage () {
Page Load event where can initialize values and call other initializers.
}

Document ready event handlers should is included from external files and inline JavaScript can is used to call the ' ready h ' Andle after any initial setup.

<script src= "My-document-ready.js" ></script>
<script>
Any global variable set-up this might be needed.
$ (document). Ready (Initpage); or $ (initpage);
</script>

Do not use the behavioral markup in HTML (JavaScript inlining), these is debugging nightmares. Always bind events with the JQuery to is consistent so it's easier to attach and remove events dynamically.

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

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

When possible, use custom for events. It's easier to unbind the exact event, that's attached without affecting other events bound to the DOM element.

$ ("#myLink"). On ("Click.myspecialclick", MyEventHandler); Good
Later on, it's easier to unbind just your click event
$ ("#myLink"). Unbind ("Click.myspecialclick");

Use if you have to attach same event to multiple elements. Event delegation allows us to attach a single event listener, to a parent element, that would fire for all descendants MATC Hing a selector, whether those descendants exist now or is added in the future.

$ ("#list a"). On ("click", Myclickhandler); Bad, your is attaching an event to all the links under the list.
$ ("#list"). On ("Click", "a", Myclickhandler); Good, only one event handler was attached to the parent.

Ajax

Avoid using. Getjson () or. get (), simply use the $.ajax () as that's what gets called internally.
Do not use the HTTP requests on HTTPS sites. Prefer schemaless URLs (leave the protocol Http/https out of your URL)
Do not put a request parameters in the URL, send them using data object setting.

Less readable ...
$.ajax ({
URL: "Something.php?param1=test1&param2=test2",
....
});

More readable ...
$.ajax ({
URL: "something.php",
Data: {param1:test1, param2:test2}
});

Try to specify the DataType setting so it's easier to know what kind of data you is working with. (see Ajax Template example below)
Use delegated event handlers for attaching events to content loaded using Ajax. Delegated events has the advantage that they can process events from descendant elements that is added to the document a T a later time (example Ajax).

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

Use Promise interface:

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

OR
var jqxhr = $.ajax ({...});
Jqxhr.done (Successhandler);
Jqxhr.fail (Failurehandler);

Sample Ajax Template:

var jqxhr = $.ajax ({
Url:url,
Type: ' Get ',//' default is Get ' and ' can use ' other ' verbs based on your needs.
Cache:true,//default is True, but false for DataType ' script ' and ' Jsonp ', so set it on need basis.
Data: {},//Add your request parameters in the data object.
DataType: "JSON",//Specify the DataType for future reference
JSONP: "Callback",//Only specify the match the name of the callback parameter your API was expecting for JSONP requests.
StatusCode: {//If you want to handle specific error codes, use the Status Code mapping settings.
404:handler404,
500:handler500
}
});
Jqxhr.done (Successhandler);
Jqxhr.fail (Failurehandler);

Effects and animations

Adopt a restrained and consistent approach to implementing animation functionality.
Do not over-do the animation effects until driven by the UX requirements.
Try to use Simeple show/hide, toggle and slideup/slidedown functionality to toggle elements.
Try to use predefined animations durations of "slow", "fast" or "a" (for medium).

Plugins

Always choose a plugin with good support, documentation, testing and community support.
Check the compatibility of plugin with the version of JQuery that is using.
Any common reusable component should be implemented as a JQuery plugin. For jQuery Plugin boilerplate code.

Chaining

Use chaining as a alternative to variable caching and multiple selector calls.

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

Whenever the chain grows over 3 links or gets complicated because of event assignment, use appropriate line breaks and IND Entation to make the code readable.

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

For long chains it was acceptable to the cache intermediate objects in a variable.

Miscellaneous

Use the Object literals for parameters.

$myLink. attr ("href", "#"). attr ("title", "My Link"). attr ("rel", "external"); Bad, 3 calls to attr ()
Good, only 1 call to attr ()
$myLink. attr ({
HREF: "#",
Title: "My Link",
Rel: "External"
});

Don't mix CSS with JQuery.

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

. error {color:red; font-weight:bold;}/* Good */

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

Do not use Deprecated Methods.  It is always important to keep a eye on deprecated methods for each new version and try avoid using them. For a list of deprecated methods.
Combine jQuery with native JavaScript when needed. See the performance difference for the example given below:

$ ("#myId"); is still little slower than ...
document.getElementById ("MyId");

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

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.