- jQuery Files
a) Try to use Jquery CDN where possible.
<script type= "text/javascript" src= "//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" ></script>
<script>window.jQuery || document.write( '<script src="js/jquery-2.1.1.min.js" type="text/javascript"><\/script>' )</script>
|
Implement a fallback to locally hosted jQuery file of same version in-case CDN is not working.(as above)
b) DO NOT use jQuery version 2.x if you support Internet Explorer 6/7/8.
c) If you are using other libraries like Prototype, MooTools, Zepto etc. that uses `$` sign as well, try not to use `$` for calling jQuery functions and instead use `jQuery` simply or use `$.noConflict()`.
- jQuery Variable
a) Better to start with `$` naming jQuery variable so it will be easy to understand and later on manipulate.
var $someDiv = $( "#someDiv" );
var string = "some string" ;
|
b) Always cache jQuery selectors object to a variable for reuse.
var $someDiv = $( "#someDiv" );
$someDiv.click(function(){
alert( 'clicked' );
});
|
c) It is recommended to use Camel Case for naming Variable.
- Selectors
a) Use ID selector whenever possible, since it uses javascript `document.getElementById()` selectors which is faster.
b) Don't use the element type in your selector when using class selector. (
for performance comparison click on :
http://jsperf.com/jqeury-selector-test)
var $something = $( "div.something" );
var $something = $( ".something" );
|
c) Use `.find()` selector. The `.find()` approach is faster because the first selection is handled without going through the Sizzle selector engine.
$( "#container div.robotarm" );
$( "#container" ).find( "div.robotarm" );
var $productIds = $( "#products div.id" );
var $productIds = $( "#products" ).find( "div.id" );
|
d) Be specific on the right-hand side of your selector, and less specific on the left.
$( "div.data .gonzalez" );
$( ".data td.gonzalez" );
|
$( ".data table.attendees td.gonzalez" );
$( ".data td.gonzalez" );
|
f) Give your Selectors a Context.
$( '.class' );
$( '.class' , '#class-container' );
|
g) Avoid Universal Selectors. More Info
$( ".buttons > *" );
$( ".buttons" ).children();
|
h) Avoid Implied Universal Selectors. When you leave off the selector, the universal selector (*) is still implied.
$( 'div.someclass :radio' );
$( 'div.someclass input:radio' );
|
i) Don’t Descend Multiple IDs or nest when selecting an ID. ID-only selections are handled using document.getElementById() so don't mix them with other selectors.
$( '#outer #inner' );
$( 'div#inner' );
$( '.outer-container #inner' );
$( '#inner' );
|
- DOM Manipulation
a) Always detach any existing element before manipulation and attach it back after manipulating it. This is reduce the Reflow and Repaint of browser and increase performance drastically or use `documentfragment`.
var $myList = $( "#list-container > ul" ).detach();
$myList.appendTo( "#list-container" );
|
var $myList = $( "#list" );
for (var i = 0 ; i < 10000 ; i++){
$myList.append( "<li>" +i+ "</li>" );
}
var $myList = $( "#list" );
var list = "" ;
for (var i = 0 ; i < 10000 ; i++){
list += "<li>" +i+ "</li>" ;
}
$myList.html(list);
var array = [];
for (var i = 0 ; i < 10000 ; i++){
array[i] = "<li>" +i+ "</li>" ;
}
$myList.html(array.join( '' ));
|
c) Make sure you check for the element in DOM before manipulating it if you are not sure about that element.
$( "#nosuchthing" ).slideUp();
var $mySelection = $( "#nosuchthing" );
if ($mySelection.length) {
$mySelection.slideUp();
}
|
Events
a) Use only one `document.ready` handler per page. It makes it easier to debug and keep track of the behavior flow.
$(document).ready(function(){.....})
$(function(){....})
|
b) DO NOT use anonymous functions to attach events. Anonymous functions are difficult to debug, maintain, test, or reuse.
$( "#myLink" ).on( "click" , function(){...});
function myLinkClickHandler(){...}
$( "#myLink" ).on( "click" , myLinkClickHandler);
|
c) Avoid Inline Javascript in HTML markup, these are debugging nightmares. Always bind events with jQuery to be consistent so it's easier to attach and remove events dynamically.
<a id= "myLink" href= "#" onclick= "myEventHandler();" >my link</a>
$( "#myLink" ).on( "click" , myEventHandler);
|
d) When possible, use custom namespace for events. It's easier to unbind the exact event that you attached without affecting other events bound to the DOM element.
$( "#myLink" ).on( "click.mySpecialClick" , myEventHandler);
$( "#myLink" ).unbind( "click.mySpecialClick" );
|
e) Use event delegation (for dynamically added element) when you have to attach same event to multiple elements. Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$( "#list a" ).on( "click" , myClickHandler);
$( "#list" ).on( "click" , "a" , myClickHandler);
|
Ajax
a) DO NOT use http requests on https sites. Prefer schemaless URLs (leave the protocol http/https out of your URL)
b) DO NOT put request parameters in the URL, send them using data object setting.
$.ajax({
url: "something.php?param1=test1¶m2=test2" ,
....
});
$.ajax({
url: "something.php" ,
data: { param1: test1, param2: test2 }
});
|
c) Try to specify the dataType setting so it's easier to know what kind of data you are working with.
d) Use Delegated event handlers for attaching events to content loaded using Ajax. Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time (example Ajax).
$( "#parent-container" ).on( "click" , "a" , delegatedClickHandlerForAjax);
|
e) Use Promise interface:
$.ajax({ ... }).then(successHandler, failureHandler);
var jqxhr = $.ajax({ ... });
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);
|
Sample Ajax Template:
var jqxhr = $.ajax({
url: url,
type: "GET" ,
cache: true ,
data: {},
dataType: "json" ,
jsonp: "callback" ,
statusCode: {
404 : handler404,
500 : handler500
}
});
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);
|
- Effects and Animations
a) Adopt a restrained and consistent approach to implementing animation functionality.
b) DO NOT over-do the animation effects until driven by the UX requirements.
c) Try to use simple `show/hide`, `toggle and slideUp/slideDown` functionality to toggle elements.
d) Try to use predefined animations durations of "slow", "fast" or 400 (for medium).
- Plugins
a) Always choose a plugin with good support, documentation, testing and community support.
b) Check the compatibility of plugin with the version of jQuery that you are using.
c) Any common reusable component should be implemented as a jQuery plugin. link to http://stefangabos.ro/jquery/jquery-plugin-boilerplate-revisited/ jQuery Plugin Boilerplate code.
Chaining
a) Use chaining as an alternative to variable caching and multiple selector calls.
$( "#myDiv" ).addClass( "error" ).show();
|
b) Whenever the chain grows over 3 links or gets complicated because of event assignment, use appropriate line breaks and indentation to make the code readable.
$( "#myLink" )
.addClass( "bold" )
.on( "click" , myClickHandler)
.on( "mouseover" , myMouseOverHandler)
.show();
|
For long chains it is acceptable to cache intermediate objects in a variable.
- Miscellaneous
a) Use Object literals for parameters.
$myLink.attr( "href" , "#" ).attr( "title" , "my link" ).attr( "rel" , "external" );
$myLink.attr({
href: "#" ,
title: "my link" ,
rel: "external"
});
|
b) Do not mix CSS with jQuery.
$( "#mydiv" ).css({ 'color' :red, 'font-weight' : 'bold' });
.error { color: red; font-weight: bold; }
$( "#mydiv" ).addClass( "error" );
|
c) DO NOT use Deprecated Methods. It is always important to keep an eye on deprecated methods for each new version and try avoid using them. Checkout
http://api.jquery.com/category/deprecated/ for a list of deprecated methods. Some of which are:
.live() (Deprecated > Deprecated 1.7 | Removed),
.load() (Deprecated > Deprecated 1.8 | Events > Document Loading),
.selector Deprecated > Deprecated 1.7 | Removed
|
$( "#myId" );
document.getElementById( "myId" );
|
- Resources
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 Cheatsheet: http://lab.abhinayrathore.com/jquery-cheatsheet/
jQuery Plugin Boilerplate: http://stefangabos.ro/jquery/jquery-plugin-boilerplate-revisited/Stackoverflow question: http://stackoverflow.com/questions/tagged/jquery
This comment has been removed by a blog administrator.
ReplyDeleteHowdy! I know this is somewhat off topic but I was wondering which blog platform are you using for this website?
ReplyDeleteOU Degree 1st Sem Result 2021
PDUSU BSC 2nd Year Result 2021
Awesome blog, thank you so much for sharing such an amazing information with us. Visit Import Globals for Vietnam Import and Export Data Services at Vietnam customs.
ReplyDeleteVietnam Import Data