jQuery and General Javascript Tips to Improve Your Code

May 19, 2013 · 72 comments

by Lars


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. Also check out: More jQuery and General Javascript Tips to Improve Your Code



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"

#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:

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

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" />

$(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()) );
   // On focus test for default saved value and if not the same clear it
   if ( $.trim($(this).val()) === $(this).data("txt") ) {
   // 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") );

Demo here

#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


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")

#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" />

//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>

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');
 .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.

 // 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')

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();


{ 10 comments… read them below or add one }

Meer Anis January 2, 2014 at 6:19 am

It’s obviously a good sharing for all. The beginners will be benefited from here.


Ashraf December 13, 2012 at 4:26 pm

Wonderful General Java script Tips. thanks


annesofie December 14, 2012 at 11:32 am

Hi Ashraf, you’re very much welcome. Just glad you found the post relevant.
Best regards, Sofie


cheap custom jerseys May 19, 2011 at 9:07 am

jQuery and General Javascript Tips to Improve Your Code


Hosting Best May 13, 2011 at 12:20 pm

Only just recently started getting into JQuery but it really pays off when you get the finished article, thanks for the write up, really useful


Rokaiya Yeasmin Munni August 5, 2010 at 8:01 am

Wonderful JavaScript tips. Thanks,,,,


jenifer c April 13, 2010 at 7:57 am
Grant @ portal software February 24, 2010 at 3:49 am

Some very nice and useful optimization tips. It’s hard to go over some old code and optimize it line by line so sometimes it’s just best to start it all from scratch, you can really see a difference after and learn more I think.


tripwiremag February 24, 2010 at 10:52 am

@Grant, agreed – re-factoring code isn’t that easy – especially languages like JavaScript. Learning new tips for future projects is important though 😉


Sunny Singh February 21, 2010 at 6:53 pm

I realy don’t see loading jQuery from Google better. There’s not an extremely high chance that the visitor has already downloaded the source, if they didn’t they have to connect to the domain first which may take a while. Not only that, but not everyone have specified the same version of jQuery, which lessens the odds of your site loading faster. If you load it from your own site (gzipped and compressed) including other scripts in the same file, you can achieve much better download speeds than relying on a third-party host.


Leave a Reply

Your email address will not be published. Required fields are marked *

{ 10 trackbacks }

Previous post:

Next post:

Web Analytics