jQuery-best-practices-and-performance-tricks

Working on the LiveBox WebApp allowed me to explore many issues related to code optimization and mobile devices performance limits.
Despite having studied how the different Layout Engines manage JavaScript instructions, DOM traversal and memory data representation, I learnt that the simplest tricks are often the ones that give more benefits.
Here are some of them.

 

1) ID and Class selector pitfalls

Class selectors are quite slow as they aim to collect an undefined number of elements; some browsers take advantage of some optimizations, but Internet Explorer will look for a class looping the whole DOM.
Labeling an element with an ID is a far better choice, but first we must make sure that the ID is unique, as jQuery states:
“Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM.”

ID selectors are very fast, but many weak or wrong usages can be found around the web:

$("div#main").addClass("home");

A tag prefix before an ID is a typical example. This selector is way slower than a simple $(“#main”) because the browser will loop through all the divs of the DOM checking their IDs.

 

2) Chaining methods

Most jQuery methods return the jQuery object, method chaining can easily avoid many useless searches through the DOM:

// bad
$("#promptDiv div.title h2").addClass("prompt");
$("#promptDiv div.title h2").html("Work complete!");
$("#promptDiv div.title h2").show();

// good
$("#promptDiv div.title h2").addClass("prompt").html("Work complete!").show();

Remember to use this syntax with moderation, as the concatenated methods will prove much less visible and readable when you’re quickly scrolling through your code.
To protect code readability, we can choose to keep methods on different lines:

// keeps all methods clearly separated
$("#promptDiv div.title h2").addClass("prompt")
                            .html("Work complete!")
                            .show();

 

3) Caching elements

When you need to use the same element multiple times as in the previous example, but also need to do some operations in the middle, a cache variable is a good solution.
Caching elements will reduce the time needed to access them each time.

var promptDiv = $("#promptDiv");
promptDiv.addClass("prompt");

// Do something

promptDiv.html("Work complete!")

// Still something to do

promptDiv.show();

Here we select an element searching for its ID (the #promptDiv); although the DOM selection of an ID is a quick operation, caching it in a variable still gives benefits in terms of time.
There are large performance improvements to be had when caching classes selectors or elements collected with more complex and time-expensive selectors.

 

4) Limit DOM manipulations

Be careful when you carry out repetitive actions. The fact that a single action seems instantaneous does not imply that executing it many (even thousands) times will keep the same performance.
Yes, I know, it’s an obvious recommendation, but strong time consuming iterations are a common trap for many coders.
DOM traversals and manipulations in long loops are often a bad and costly practice.

// Bad
elements.each(function() {
    $("#container").append( $(this).html());
});

Iterating all elements this way will perform a #container ID search operation for each element.
We can easily speedup this function by caching the container element:

// Not too bad
var container = $("#container");

elements.each(function() {
    container.append( $(this).html() );
});

We already saw this optimization in the previous example, but the question is, can we do more?
An even better solution is to adopt string concatenation followed by a single DOM manipulation instead of multiple DOM manipulations:

// Good
var content = '';

elements.each(function() {
    content += $(this).html();
});

$("#container").append(content);

As we’ve just seen, good results in terms of performance can be achieved with a really small effort.
Writing code that works is often the only goal, but it is way more satisfying to write code that works well.

jQuery best practices and performance tricks

Leave a Reply