jQuery best practices, part I

jQuery best practices, part I

Every front-end developer uses jQuery. It is a powerful JavaScript library, which greatly simplifies front-end development.

jQuery's way of work is to select something in the HTML DOM (Document Object Model, or HTML document) and do something with it. This is a good and powerful thing -- and with this power comes responsibility. It is important to understand what goes on behind the scenes in order to make code efficient and not overloading the browser resources.

An HTML document is a tree like structure. Therefore when you select something with jQuery the engine of the library traverses the tree to get hold of your desired element. Each such call costs resources. And here comes the first rule!

Always cache/store jQuery objects.

Consider this example:

$('.myClass').hide();
$('.myClass).html('<b>My super fine HTML</b>');
$('.myClass).doStaff();

Each time you write $('.myClass') you traverse the DOM tree. Imagine you have an application which has to do that thousand of times!

What you must do is to cache $('.myClass') jQuery object, like so:

var $cachedClass = $('.myClass');

From now on you can refer to $cachedClass to refer to $('.myClass') object, and that saves many resources. As a side note it is a good practice to prefix cached objects with $.

Optimize selectors

jQuery is a JavaScript library. Therefore, it is always faster to use native JavaScript where it fits. The most common case is to use JavaScript native document.getElementById(), instead of jQuery version $('#myElement'). And if you have the chance always select elements by Id. This is the fastest way to do it.

Do not use element type in you selectors:

var $el = $("div.myEl"); // Slow
var $el = $(".myEl"); // Fast

Use find when looking for child in selected Id:

$('#elId div.items') // Fast
 $('#elId').find('div.items') // Extra super fast

And be specific on the right hand selectors and less specific on the left ones to make selections faster.

$('.buttons > *') // Extra super expensive
$('.buttons').children() // A way better

You can also define context for the elements you are looking for, like so:

$('.myPrecious', '#gollumId') // myPrecious class will be searched for inside gollumId.

Appending elements

Appending elements to the DOM is extra expensive. Avoid multiple appends by using these simple techniques.

To illustrate I take the code from a project I was working on. I needed to build elements and append them to DOM. First the wrong way of doing it:

var $telcomContainer = $('#mj-telecommando-container').find('ul');

for (var key in telecommandoData) {
$telcomContainer.append($('<span/>', {"id":"icon" + secondPartOfId,
"class":"mj-telecom-icon"}));
}

Imaging now that the for-loop will be running 100 of times. This is going to be very bad. Hundreds of appends!

This is the right way to do it:

var $telcomContainer = $('#mj-telecommando-container').find('ul');
var telcomItems = []; // we declare an array

for (var key in telecommandoData) {
telcomItems [key] = $('<span/>', {"id":"icon" + key, "class":"mj-telecom
-icon"})); // put all the items to array
}

I use here appendEach(). This is not a jQuery command, but a small handy plugin. The source code is here:

// JQUERY PLUGIN: Appends each jQuery object (in an array of
// jQuery objects) to the currently selected collection.
// @source: http://www.bennadel.com/blog/2268-appending-an-array-of-jquery-objects-to-the-dom.htm

define(['jquery'], function($){
    $.fn.appendEach = function( arrayOfWrappers ){

    // Map the array of jQuery objects to an array of
    // raw DOM nodes.
       var rawArray = jQuery.map(
         arrayOfWrappers,
         function( value, index ){

          // Return the unwrapped version. This will return
          // the underlying DOM nodes contained within each
          // jQuery value.
          return( value.get() );

      }
    );

     // Add the raw DOM array to the current collection.
     this.append( rawArray ); 

     // Return this reference to maintain method chaining.
  
   return( this );

  };
});

More tips coming in the next part. Enjoy so far and feel free to comment:)

 

 

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