I have published several articles describing the many benefits we can all get from using jquery. Having access to many good plugins, examples and tutorials is important to get great ideas turned into excellent solutions as fast and elegant as possible and that is what jquery is all about. If you use jquery regularly or plan to start using it as more and more web developers tend to do I believe a few fundamentals and best practice tips to improve your jquery code will be worth spending a few minutes on. Please don’t hesitate to post a comment with your own tips and suggestions.
jQuery Tips
#1 – Load the framework from Google Code
Google have been hosting several JavaScript libraries for a while now on Google Code and you may want to load it from them instead of from your server.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
type="text/javascript"></script>
#2 – Storing Data
Use data method and avoid storing data inside the DOM. Some developers have a habit of storing data in the HTML attributes like fx.:
$('selector').attr('alt', 'data being stored');
// later the data can be retrieved using:
$('selector').attr('alt');
HTML attributes is not meant to store data like that and the “alt” as a parameter name does not really make sense.
The right alternative in most cases is using the data method in jQuery. It allows you to associate data with an element on the page.
$('selector').data('paramtername', 'data being stored');
// then later getting the data with
$('selector').data('paramtername');
This approach allows you to store data with meaningful names and it is more flexible as you can store as much data as you want on any element on the page. For more information about data() and removeData(), see here jQuery internals
One classical use of this is saving the default value of a input field because you want to clear it on focus.
<form id="testform">
<input type="text" class="clear" value="Always cleared" />
<input type="text" class="clear once" value="Cleared only once" />
<input type="text" value="Normal text" />
</form>
$(function() {
//Go through every input field with clear class using each function
//(NB! "clear once" is two classes clear and once)
$('#testform input.clear').each(function(){
//use the data function to save the data
$(this).data( "txt", $.trim($(this).val()) );
}).focus(function(){
// On focus test for default saved value and if not the same clear it
if ( $.trim($(this).val()) === $(this).data("txt") ) {
$(this).val("");
}
}).blur(function(){
// Use blur event to reset default value in field that have class clear
// but ignore if class once is present
if ( $.trim($(this).val()) === "" && !$(this).hasClass("once") ) {
//Restore saved data
$(this).val( $(this).data("txt") );
}
});
});
#3 – Use Cheat Sheets
Most people can’t remember a lot of details and even though programmers tend to be better that the average the amount of information they need to have instant access too is devastating. Having a few cheat sheets printed out and placed next to the monitor is a good idea to speed up programming and to improve the code quality.
oscarotero jquery 1.3 (as wallpaper)
jQuery 1.3 Cheat Sheet
Quick reference to all jQuery 1.3 functions and properties. Note that it doesn't cover any of the UI functionality as this could easily be a whole cheat sheet in and of itself.
#4 – Minimize download time
Most browsers only download one script at the time and if you have several scripts being loaded on every page it can impact your download time.
You can use Dean Edwards service “packer” to compress your scripts and make download faster. You need to maintain a development version and a runtime version as all you in-line comments will be lost. You will find it here.
Another solution that take this to the extreme is interesting to take a look at. Basically it is a server based PHP script that combine javasctipt files and compress them in a easy to maintain approach. Take a look at and see if you can use the idea and some elements of the concept “Make your pages load faster by combining and compressing javascript and css files“.
#5 – Logging to the Firebug console in jQuery
Firebug is one of my favourite Firefox extensions providing tons of tools in a very usable structure to aid you in HTML+CSS+JavaScript development. Obviously it is worth having just for it’s excellent inspection feature allowing you to jump into the html and css and learn in a visual way what elements of the page is rendered by what code. As a jQuery and general Javascript developer Firefox also has good support for logging in your JavaScript code.
The easiest way to write to the Firebug console looks like this:
console.log("hello world")
You can pass as many arguments as you want and they will be joined together in a row, like
console.log(2,4,6,8,"foo",bar)
As a jQuery developer it even gets better using a tiny extension that Dominic Mitchell came up with to log any jQuery object to the console .
jQuery.fn.log = function (msg) {
console.log("%s: %o", msg, this);
return this;
};
With this extension you can simply call .log() on the object you are currently addressing fx.:
$('#some_div').find('li.source > input:checkbox')
.log("sources to uncheck")
.removeAttr("checked");
#6 – Use ID as Selector whenever possible
Selecting DOM elements using the class attribute is simpler than ever using jQuery. Even though it is simple it should be avoided whenever possible as as selecting using ID is much faster (In IE the class selector seams to loop through the entire DOM why generally it should be avoided). Selecting elements using IDs is fast because the browsers have the native getElementByID method that jQuery will use for IDs. Selecting classes still requires the DOM to be traversed behind the scene and if it is a large DOM and you make several lookups the performance impact can be significant. Let take a look at this simple html code:
<div id="main">
<form method="post" action="/">
<h2>Selectors in jQuery</h2>
...
...
<input class="button" id="main_button" type="submit" value="Submit" />
</form>
</div>
...
//Selecting the submit button using the class attribute
//like this is much slower than...
var main_button = $('#main .button');
//Selecting the submit button directly using the id like this
var main_button = $('#main_button');
#7 – Use Tags Before Classes
When you are selecting through tags jQuery will use the native browser JavaScript method, getElementsByTagName(). ID is still faster but this is still much faster than selecting with a class name.
<ul id="shopping_cart_items">
<li><input class="in_stock" name="item" type="radio" value="Item-X" /> Item X</li>
<li><input class="3-5_days" name="item" type="radio" value="Item-Y" /> Item Y</li>
<li><input class="unknown" name="item" type="radio" value="Item-Z" /> Item Z</li>
</ul>
It is important to prefix a class with a tag name (here this is “input”) and then it is important to descend from an ID to limit the scope of the selection:
var in_stock = $('#shopping_cart_items input.in_stock');
#8 – Cache jQuery Objects
Caching an object before working with it is essential for performance. You should neverdo like this:
<li>Description: <input type="text" name="description" value="" /></li>
...
$('#shopping_cart_items input.text').css('border', '3px dashed yellow');
$('#shopping_cart_items input.text').css('background-color', 'red');
$('#shopping_cart_items input.text').val("text updated");
In stead cache the object and work on it. The example below should really use chaining but it is just for illustration.
var input_text = $('#shopping_cart_items input.text');
input_text.css('border', '3px dashed yellow');
input_text.css('background-color', 'red');
input_text.val("text updated");
//same with chaining:
var input_text = $('#shopping_cart_items input.text');
input_text
.css('border', '3px dashed yellow')
.css('background-color', 'red')
.val("text updated");
#9 – Bind certain jQuery functions to $(window).load event
Most jQuery code examples and tutorials instruct us to bind our jQuery code to the $(document).ready event. In many cases this is OK but since $(document).ready occurs during page render while objects are still downloading it may cause problems for some types of scripts. Functionality such as binding visual effects and animations, drag and drop, pre-fetching hidden images etc. could benefit from being bound to the $(window).load as it will ensure that all dependant elements are ready for use.
$(window).load(function(){
// Put your jQuery functions that should only initialize after the page has loaded.
});
#10 – Use Chaining to limit selectors, make the code more simple and elegant
Because JavaScript supports chaining and because it works across line breaks you can structure your code like this. This example first removes a class on an element and then adds another to the same element.
$('#shopping_cart_items input.in_stock')
.removeClass('in_stock')
.addClass('3-5_days');
If needed it is really simple and useful as well to create a jQuery function that support chaining.
$.fn.makeNotInStock = function() {
return $(this).removeClass('in_stock').addClass('3-5_days');
}
$('#shopping_cart_items input.in_stock').makeNotInStock().log();
|