jquery coding standard
Introduction
Anybody can write code. With a few months of programming experience, you can write 'working applications'. Making it work is easy, but doing it the right way requires more work, than just making it work.
Believe it, majority of the programmers write 'working code', but not ‘good code'. Writing 'good code' is an art and you must learn and practice it.
Everyone may have
different definitions for the term ‘good code’. But the following
are the characteristics of good code.
- Reliable
- Maintainable
- Efficient
Most of the developers
are inclined towards writing code for higher performance,
compromising reliability and maintainability. But considering the
long term ROI (Return On Investment), efficiency and performance
comes below reliability and maintainability. If your code is not
reliable and maintainable, you will be spending lot of time to
identify issues, trying to understand code etc throughout the life of
your application.
Purpose of coding standards and best practices
To develop reliable and maintainable applications, you must follow
coding standards and best practices.
The naming conventions, coding standards and best practices described
in this document are compiled from our own experience and by
referring to various JQuery guidelines.
Plugins:
- Please avoid unnecessary use of plugins
- If a plugin is being used, respect the authors work and ensure that the plugin file is reused with the license comments intact
- If you are writing a reusable functionality in the code, always move it into a jQuery plugin format, to be reused across the site
Coding:
- Use jQuery CDN (google or Microsoft or jQuery) as much as possible for script registration, if its fine with clients. To be on the safer side, you could have a fallback code as well:<!– Grab Google CDN jQuery. fall back to local if necessary –>
<script
src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js“></script>
<script>!window.jQuery &&
document.write(‘<script
src=”js/jquery-1.4.2.min.js”><\/script>’)</script>
- Avoid unnecessary upgrades of jQuery, unless there are features, which you require or some plugins require. Stick to one version from the beginning. (ex. 1.5.1)
- Avoid writing event handler attributes (onclick etc.), instead use live or bind methods to attach the respective event handlers.
- Avoid mixing javascript code with jQuery code.
- Cache any jQuery selector, if reused in multiple statements.
- Ex. Avoid $(“#x”).val(); $(“#x”).attr(“align”,”right”); Use var $x = $(“#x”); $x.val();$x.attr(“align”,”right”);
- Ensure that you place ready function in your code. $(document).ready(function(){});
- Use find method, instead of building a complex jQuery selector.
/Fine in modern browsers,
though Sizzle does begin “running”
$(‘#someDiv p.someClass’).hide();
// Better for all browsers, and Sizzle never inits.
$(‘#someDiv’).find(‘p.someClass’).hide();
- Avoid misusing $(this).
- Ex. Use this.id instead of $(this).attr(‘id’)
- Keep your code safe, by using noConflict() method or by passing jQuery.
Ex. (function($){})(jQuery); or by wrapping it in a ready method. - Use $.ajax instead of $.get or $.getJSON, because internally they call $.ajax.
- Use JSON formats for communications.
- Ensure that you move your jQuery codes to a separate javascript file, instead of inline scripts.
- Compress javascript files for better performance.
Debugging:
- Use Developer Toolbars and Inspectors to debug your code from client side. You do not need to perform deployments and builds to debug your jQuery code(s).
Limit Direct DOM Manipulation
The
basic idea here is to create exactly what you need in memory, and
then
update the DOM. This is not a jQuery best practice, but a must for
efficient JavaScript. Direct
DOM manipulation is slow.
For example, if you need to dynamically create a list of elements, do
not do this:
var top_100_list = [...], // assume
this has 100 unique strings
$mylist = $('#mylist'); //
jQuery selects our <ul> element
for (var i=0,
l=top_100_list.length; i<l; i++)
{
$mylist.append('<li>' +
top_100_list[i] + '</li>');
}
Instead, we want to create the
entire set of elements in a string before inserting into the DOM:
var top_100_list = [...], // assume
this has 100 unique strings
$mylist = $('#mylist'), //
jQuery selects our <ul> element
top_100_li = ""; //
This will store our list items
for (var i=0,
l=top_100_list.length; i<l; i++)
{
top_100_li += '<li>' +
top_100_list[i] + '</li>';
}
$mylist.html(top_100_li);
Even
faster, we should always wrap many elements
in a single parent node before insertion:
var top_100_list = [...], // assume
this has 100 unique strings
$mylist = $('#mylist'), //
jQuery selects our <ul> element
top_100_ul = '<ul
id="#mylist">'; // This will store our entire unordered
list
for (var i=0,
l=top_100_list.length; i<l; i++)
{
top_100_ul += '<li>' +
top_100_list[i] + '</li>';
}
top_100_ul += '</ul>'; //
Close our unordered list
$mylist.replaceWith(top_100_ul);
If you do the above and are still
concerned about performance:
- Give jQuery’s clone() method a try. This creates a copy of the node tree, which you can manipulate “off-line” and then insert back in when you are ready.
- Use DOM DocumentFragments. As the creator of jQuery points out, they perform much better than direct DOM manipulation. The idea would be to create what you need (similar to what we did above with a string), and use the jQuery insert or replace methods.
Always Descend From an #id
- The fastest selector in jQuery is the ID selector ($('#someid')). This is because it maps directly to a native JavaScript method, getElementById().
Selecting Single Elements
<div id="content">
<form method="post"
action="/">
<h2>Traffic
Light</h2>
<ul id="traffic_light">
<li><input
type="radio" class="on" name="light"
value="red" /> Red</li>
<li><input
type="radio" class="off" name="light"
value="yellow" /> Yellow</li>
<li><input
type="radio" class="off" name="light"
value="green" /> Green</li>
</ul>
<input class="button"
id="traffic_button" type="submit" value="Go"
/>
</form>
</div>
Selecting the button like this is
slower:
var traffic_button = $('#content
.button');
Instead, select the button
directly:
var traffic_button =
$('#traffic_button');
Selecting
Multiple ElementsOnce we start talking about selecting multiple
elements, we are really talking about DOM traversal and looping,
something that is slow. To minimize the performance hit, always
descend from the closest parent ID:
var traffic_lights =
$('#traffic_light input');
Comments
Post a Comment