jQuery Best Practices

Introduction

jQuery is one of the most used JavaScript libraries today, if not the most. More and more plugins are being released, and people use it to add cool and useful functionalities to their webpages.

I always take a look at other people code, to see if I spot some new interesting tecnique, or just for curiosity. What I found most, is that too often people make many mistakes, or write code in a bad way.

In my years of programming with both JavaScript and jQuery I made many mistakes, and understand a lot of things that changed the way I code my scripts or plugins. This resulted in quicker page loads, less bugs, increased compatibility between browsers, smaller code size, better code readability, better user experience, and more…

$()

One of the most used features of jQuery is indeed its ability to retrieve a DOM element simply passing a reference to the $() function, be it an ID or class or whatever.

$( '#foo' ).dosomething();

Everytime we use this function jQuery search for the DOM element, and if the element is found it creates an object representing a clone of that element, with added capabilities. This is true even for elements we already found using this function, so calling this function for the same elements more than once is redundant.

// This is BAD practice!!!

$( '#foo' ).hide();
$( '#foo' ).css( 'color', 'red' );
$( '#foo' ).show();

Instead of calling the $() function multiple times for the same element, wasting time and resources, we should always keep a reference of the found elements in a variable, and use it everytime we need the same element.

// Good practice

var $foo = $( '#foo' );

$foo.hide();
$foo.css( 'color', 'red' );
$foo.show();

Chaining

In the previous example, we called for three consecutive times a method on the object $foo. But instead of repeating each time the $foo variable, we should use the chaining functionality jQuery offers.

Most jQuery methods returns the same object which we called the method on, so we can then call another method right after the end of the previous one.

// Good practice

$foo.hide().css( 'color', 'red' ).show();

Object Literals for Parameters

Did you know that many jQuery methods can take a JavaScript object literal as a parameter?

For those who don’t know, an object literal is a set of key:value pairs separated by commas, inside curly braces.

// example of object literal

{
  'name': 'Foo',
  'surname': 'Bar',
  'age': 26
}

Passing an object literal as a parameter for jQuery methods avoid the need of calling the same method more than once. Take a look at the following code:

// the css method is being called three different times on the same object

var $foo = $( '#foo' );

$foo.css( 'color', 'red' );
$foo.css( 'width', '200px' );
$foo.css( 'height', '200px' );

Instead, we can call the css method only one time by passing an object literal as a parameter, like this:

// passing object literals as parameters is good practice

var $foo = $( '#foo' );

$foo.css({
  'color': 'red',
  'width': '200px',
  'height': '200px'
});

Use ID Selector Whenever Possible

Finding a DOM element by its ID is the fastest way, both in JavaScript and in jQuery. Whenever possible, you should always use the ID selector instead of using classes or tag names, or other ways.

Also, when finding an element by its ID with the $() function, there’s no need to specify a context, since it’s slower than without.

// Faster
$( '#foo' );

// Slower
$( '#foo', this );

Don’t Mix CSS with jQuery

Instead of changing CSS values with jQuery, you should use classes to change the appearance of elements. This way you can keep all your CSS in your CSS files, specify different appearances for different classes, and use jQuery to add or remove classes to apply your CSS.

For this we can use .addClass() and .removeClass() methods.

Specify different classes in the CSS

.red {
  color: red;
}
.blue {
  color: blue;
}

Then use jQuery to add or remove classes to objects.

// add 'blue' class to each 'p' element
$( 'p' ).addClass( 'blue' );

// if we want to change the text color to red, we remove the blue class and add the red one
$( 'p' ).removeClass( 'blue' ).addClass( 'red' );

Avoid multiple $(document).ready() calls

Executing code only after the DOM has been fully created, or the page content being fully loaded, is a good way of executing scripts. But it’s unnecessary to repeat $(document).ready() or $(window).load() for each script you want to run.

Better to just use it only once, and put your code inside a function.

$( document ).ready( function () {

  // all your code here

});

$( window ).load( function () {

  // all your code here

});

Understand jQuery Selector

One of the most powerful features of jQuery is the great possibilities offered to find DOM elements. What many people don’t know though, is that DOM elements may not only be found using ID or class selector, but also with many other powerful selectors.

Here you can find the complete list of all jQuery selectors.

Learn DOM Traversing

Another powerful feature which will make your life easier is the collection of many methods to traverse the DOM.

Starting from an element, you can find its parents or children, get the next or previous element from a list or elements, find only the elements with properties you specify, and much more.

Here’s the list of all jQuery traversing methods.