Top 5 jQuery tips for your site

Posted on Monday June 06, 2011 / by Eric Potvin

Load the framework from Google Code

Google is hosting several JavaScript libraries. The advantages of using Google are simple:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"; type="text/javascript"></script>

Keep DOM manipulation to a minimum

When you need to concatenate strings, do not use the DOM each time you loop through records or array. Operation such as .append() or .prepend() can be costly and can slow down your script. To improve performance, simply create a temporary variable and concatenate the results to it.

For example:

var list = $('input:checkbox:checked'); // we have over 100
var len = list.length;

for (i=0; i < len; ++i){
    $('#result').append(list[i].value);
}

Can be optimized by doing:

var list = $('input:checkbox:checked');
var len = list.length;
var result = '';
for (i=0; i < len; ++i){
    result += list[i].value;
}  
$('#result').html(result);

Use IDs instead of classes wherever possible

The fastest way to select an item in jQuery is to use the ID selector ($('#id')) which is mapped directly to a native JavaScript method, getElementById(). For example, we have this code sample:

<div id="content">
    <div id="wrapperLeft">
        <h1>Page Title</h1>
        <h4>Article Title</h4>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus augue enim, imperdiet sed dignissim non, rutrum at orci.
            Etiam pharetra mi sit amet erat consequat a tincidunt neque accumsan. Cras ut est ligula, vitae cursus purus. Cras non velit leo.
            Mauris sit amet ipsum tortor. Nulla justo orci, auctor in egestas sed, varius tempor ligula.
            Nam pretium neque at dui consectetur et tempor nulla tristique.
        </p>
        <p>
            Sed rhoncus, massa vel dapibus dignissim, mauris nulla consequat nibh, suscipit molestie nisl urna nec mi.
            Ut a leo eget dolor scelerisque blandit ut facilisis mi.
            In et justo in leo vestibulum malesuada sed sed augue. Integer magna nibh, auctor rhoncus porttitor quis, egestas at lorem.
            Vestibulum magna neque, consectetur ut adipiscing suscipit, luctus quis ligula. Nunc id leo ac nulla semper placerat.
        </p>
        <div>
            <h6>Send your comment</h6>
            <form>
                Name: <input type="text">
                Comment: <textarea></textarea>
                <input type="submit" class="sendComment">
            </form>
        </div>
    </div>
    <div id="wrapperRight">
        <h6>Signup for our newsletter</h6>
        <form>
            Name: <input type="text">
            email: <input type="text">
            <input type="submit" class="newsletter">
        </form>
    </div>
</div>

In this case, we will have to call the submit button this way:

$('#content #wrapperLeft .sendComment');

To fix this, simply use a unique ID for each button and then call then with their respective id.

$('#sendComment');

Use For Instead of Each

Native JavaScript functions are always faster than any custom or jQuery functions. However, it is easier to use these custom functions when looping through an XML or jSon object. If you can, always use the native loops (for, while, do while). Here's some benchmark using native and jQuery .each function.

var array = new Array ();  
for (var i=0; i<10000; ++i) {  
    array[i] = 0;  
}  

Using the for loop:

console.time('native');  
var len = array.length;  
for (var i=0;i<len; ++i) {  
    array[i] = i;
}  
console.timeEnd('native');  

Result: 0ms

Using .each function

console.time('jquery');  
$.each (array, function (i) {  
    array[i] = i;  
});  
console.timeEnd('jquery');  

Result: 3ms

Do not call selector over and over and over and over ...

$('div.message').css('color', 'red');
$('div.message').css('font', 'red');
$('div.message').css('background-color', '#eee');
$('div.message').css('font-size', '16px');
$('div.message').css('font-weight' : 'bold');
$('div.message').css('text-align' : 'center');
$('div.message').html('Your name is required');
$('div.message').fadeIn('fast');

Instead write:

$('div.message')
    .css({
        'color', 'red',
        'font', 'red',
        'background-color', '#eee',
        'font-size', '16px',
        'font-weight' : 'bold',
        'text-align' : 'center',
    })
    .html('Your name is required')
    .fadeIn('fast');