jQuery
is an extremely powerful library that provides all the tools necessary to
create beautiful interactions and animations in web pages, while empowering the
developer to do so in an accessible and degradable manner. Here I'll write some of best practices one should use while working with client side scripting.
·
If you are registering script files through code behind, its good practice to register all javascript/jquery files on page_init, and if you need to register on the fly scripts from code behind then register those scripts in PreRenderComplete event.
· Use the jQuery shorthand $ where possible:
$(function() { ... });
$(document).ready(function() { ... }); |
·
Use a document ready event in place of
window onload. The handler for the document ready event must be an anonymous
declared in the following form:
$(document).ready(function(){
});
Instead of:
$().ready(handler);
|
·
If you want to use jQuery’s $ variable,
wrap your code like this:
(function ($) {
})(jQuery); |
- Use tabs to indent your code. Be sure to use liberal spacing in your code.
// Avoid:
if (msg === "test") {
foo("abc", "def", {
data: 1 });
}
// Correct:
if (msg === "test") {
foo("abc", "def", {
data: 1
});
}
|
- If you want to use global variables within the scope of your code, wrap your code like this:
(function () {
|
·
Long comments should use /* ... */. Single
line comments should always be on their own line and be above the line they
reference. For example:
// We're going to loop here
for (var i = 0; i
< 10; i++) { }
|
·
Strict equality checks (===) should be used
in favor of == wherever possible.
·
if/else/for/while/try always have braces
and always go on multiple lines.
// Avoid:
if (true)
test();
// Correct:
if (true) {
test();
}
|
·
Don't put statements on the same line as a
conditional. For example:
// Avoid:
if ( true ) return;
// Correct:
if ( true ) {
return;
|
·
Assignments should always have a semicolon
after them. Semicolons should always be followed by an endline. Assignments in
a declaration should always be on their own line. Declarations that don't have
an assignment should be listed together at the start of the declaration.
·
All RegExp operations should be done using
.test() and .exec(). "string".match() is no longer used.
·
Avoid Internet Explorer errors
o
Declare all local variables with var before
they are used.
o
Remove trailing commas from array and
object definitions, i.e.:
var object = { foo: 'test' }
instead of
var object = { foo: 'test', }
|
·
Use #Id selector wherever possible. It is
the fastest. Selectors are ranked by performance as follows:
o
#Id
o
Element
o
.class, :pseudoclass and :custom
The Class and PseudoClass and Custom
selectors are slower than ID and Element selectors. The deficiency of their
performance can be mitigated by combining them with other selector types, so do
this wherever possible.
Examples
$(".odd"); //Inefficient: scans DOM for all elements
with odd class
$("tr.odd");//More efficient:
Searches only <tr>s with odd class
$("#MyTable
tr.odd");//More efficient: searches descendents of #MyTable
$("#MyTable>tbody>tr.odd"); //Best:
searches immediate children
|
·
Avoid using direct CSS style changes using
.css()and inbuilt style functions, i.e. .length() or .width(), Instead, declare
the styles in a class within a CSS Style Sheet file (not inline within an HTML
file), and use .addClass(), .removeClass() or .toggleClass() upon your selected
object(s). For example:
$("#oddRow").css({
"background-color":"gray"
});
Use instead:
$("#oddRow").addClass("alternateRow");
/*In CSS File:*/
.alternateRow
{
background-color:gray;
}
|
·
No JavaScript or behavioural markup is to
be included in HTML files. For example, the red-highlighted code should not be
present in HTML any more:
<input type="button" id="TestButton" onclick="TestClickButton()">
|
·
Use the shorthand event syntax:
$("#TestButton").click(TestFunc); //use this
$("#TestButton").bind("click", TestFunc); //instead
of this
|
·
There is often a requirement to store/cache
a jQuery selection in a holding variable. Where this is the case, you should
prefix the variable name with a ‘$’. For example:
var $this = $(this);
var $FormTable = $("#formTable");
$FormTable.addClass("testClass");
$FormTable.append("<tr></tr>");
|
·
Chaining is one of the
signature features of jQuery. Used correctly, it can reduce the amount of code
we have to write and the amount of data that is held in memory. The above
example could have been written efficiently as a chain like so:
$("#formTable").addClass("testClass").append("<tr></tr>");
|
Chaining can be considered as an alternative to:
o
Caching jQuery objects in
local variables
o
Performing multiple
selections
However for long chains, finding and defining a formatting and
indentation strategy can be troublesome. It can be better in these instances to
cache your jQuery object in a separate variable.
Comments
Post a Comment