jQuery best practices, part II

jQuery best practices, part II

jQuery is a powerful JavaScript library that simplifies manipulation of HTML documents. In part one I touched upon the topics of caching jQuery objects, optimizing selectors and append operations -- making your code more efficient and utilizing much less browser resources. Here I come with some more tricks.

Do not nest ids

I wrote in the first part that the use of id when selecting an element is preferable. But nesting ids is not good. If you have to nest ids then it should be a class, not id. Consider this example:

$(‘#element-wrapper #wrapper-content’); // Bad
$(‘div#wrapper-content’); // Bad, no point to call for ‘div’ here
$(‘.element-wrapper-class #wrapper-content’) // Also bad, not need for class call ‘.element-wrapper-class’
$(‘#wrapper-content’) // This is all you need to get hold of ‘#wrapper-content’ efficiently

Do not act on absent elements

Do not launch the whole jQuery traverse operation if you know that element might be absent:

$(‘#no-such-element’).toggle(); // Bad. Three functions are run here before jQuery realized that there is nothing to select.

The way to do it is always check if the desired selection is not empty, like so:

var $my-element = $(‘.no-such-element’);
if($my-element.length){
    $(‘.no-such-element’).toggle();
}

Use event delegation

Use event delegation when you attach the same events to multiple elements under one parent. If you use event delegation you attach event listener to a parent element and this event will fire on all descendant elements whether this descendant elements exist now or will be added later during the app run.

First, the bad example:

$(‘#telecommando-container li’).on(‘click’, function(){
// your click function
});

You attach in the code above click-event to each li. This is not good. If you know that you will have multiple ‘li’s under element with id ‘telecommando-container’ you should assign click event to parent, like so:

$('#telecommando-container').on('click', 'li', function(event){
var $me = $(this); // Cached telecommando clicked element
     if($me.attr('data-state') == '1'){
        $me.attr('data-state', '0');
        _saveWidgetState($me);
     } else if ($me.attr('data-state') == '0'){
        $me.attr('data-state', '1');
        _saveWidgetState($me);
     } else{…}
});

Observe that you can then perform different actions depending on what element is selected. And – most importantly – only one event is attached here, not multiple events for each li element which you would have to handle individually.

Do not use behavioral markup in HTML

You have probably seen a code like this:

<a id=”my-great-link” href=”#” onclick=”myLinkHandler();”>My link</a>

This is bad. ‘onclick=” myLinkHandler();” is going to be a debugging nightmare.

Be consistent and attach and remove events dynamically with jQuery, like so:

$(‘#my-great-link’).on(‘click’, function(){
     // your handler here
});

Or by calling a function:

$(‘#my-great-link’).on(‘click’, myLinkHandler);

Use chaining in jQuery

You can use in some cases chaining as alternative to caching or – what is much worse – multiple selector calls:

$(‘#myID’).addClass(‘error’).show();

Or if the chain grows, like so:

$(‘#myID’)
     .addClass(‘error’)
     .on(‘click’, myClickHandler)
     .show();

Use object literals for parameters

Instead of writing something like this:

$myElement.attr(‘href’, ‘#’).attr(‘title’,‘My element’).attr(‘text’, ‘My text’);

where you make three unnecessary calls to attr, write the code like this:

$myElement.attr({
     href: ‘#’,
     title: ‘My element’,
     text: ‘My text’
});

Try to avoid mixing CSS and jQuery

Every now and then you will be tempted to write something like this:

$(‘#my-element’).css({‘color’: pink, ‘font-weight’: ‘bold’});

Resist this temptation. Instead use classes described in your css style sheet for that, like so:

$(‘#my-element’).addClass(‘pinky’);

In your css stylesheet:

.pinky{
     color: pink;
     font-weight: bold;
}

That´s all folks for now. Please, drop a comment if you have any questions or suggestions.

 

Om bloggeren:
Igor Koudrik har Master i Computer Science fra Universitetet i Oslo og laget sin første html-side i 1996. Han er en lidenskapelig front-end utvikler som alltid er oppdatert på ny teknologi og nye løsninger.

comments powered by Disqus