Skip to content

jQuery Best Practices

Stephen A Thomas edited this page Nov 19, 2013 · 2 revisions

Here is a quick summary of some of the best practices for using jQuery on a web site. By no means are these original to me; rather, I’ve compiled them from several presentations, tutorials, and other posts. The real authors include noted JavaScript experts such as Addy Osmani and Paul Irish. (The complete list is at the end of the article.)

Use $ Prefix for Variables Containing jQuery Selections

Variables that store jQuery selections should use the $ as the first character in their names.

Bad:

var el = $('#id');

Good:

var $el = $('#id');

Source(s): [Artz]

Take advantage of jQuery Chaining

Bad:

$el.addClass('class');
$el.on('click',fn);
$el.css('opacity', '1.0');

Good:

$el.addClass('class').on('click',fn).css('opacity', '1.0');

Source(s): [Artz], [Buckler], [Didier], [Faeti], [Franko], [Osmani], [Way]

Use $.find()

Use the jQuery .find() method instead of specifying an explicit context when making a selection.

Bad:

var $outer = $('#id-outer');
var $inner = $('#id-inner', $outer);

Good:

var $outer = $('#id-outer');
var $inner = $outer.find('#id-inner');

Source(s): [Artz], [Irish], [Lal], [Osmani], [Way]

Take Advantage of $.Deferred

From the jQuery API:

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Bad:

$.ajax('url/path', {
	success: function(response) {
		// process response
	}
});

Good:

$.ajax('url/path').done(function(response) {
	// process response
});

Source(s): [Didier], [Franko]

Use Object Literals

Combine properties into a single object literal.

Bad:

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

Good:

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

Source(s): [Faeti], [Lal], [Way]

Use Efficient Selections

When selecting elements, descend from an id if possible, otherwise use a tag name. Avoid using a class name without a tag name.

Bad:

var $el = $('.class');

Better:

var $el = $('div.class');

Best:

var $el = $('#id');

Source(s): [Artz], [Buckler], [Didier], [Faeti], [Franko], [Irish], [LPRocksIT], [Osmani]

Select Specific First

For multi-level selections, narrow to the most specific selector first. And note that jQuery processes selectors from right to left.

Bad:

var $el = $('#id em');

Because jQuery will first find every <em> in the entire document and then look for the id (right to left).

Good:

var $el = $('#id').find('em');

Source(s): [Buckler], [Didier], [Franko], [Irish], [LPRocksIT]

Cache Selections

Unless the selection is dynamic and subject to change, cache the result of a jQuery selection in a JavaScript variable.

Bad:

$('#id').addClass('class');
//...
$('#id').removeClass('class');

Good:

var $el = $('#id');
$el.addClass('class');
//...
$el.removeClass('class');

Source(s): [Artz], [Buckler], [Didier], [Faeti], [Franko], [Lal], [LPRocksIT], [Osmani], [Way]

Use Sub-Queries

When possible, select from within a previously cached selection rather than selecting from the entire DOM.

Bad:

var $outer = $('#id-outer');
var $inner = $('#id-inner');

Good:

var $outer = $('#id-outer');
var $inner = $outer.find('#id-inner');

Source(s): [Artz]

Limit Direct DOM Manipulation

Perform as much processing as possible on elements that are detached from the DOM.

Bad:

$('html').append($('<ul/>'));
for (var i=0; i<100; i++) {
	$('ul').append($("<li/>"));
}

Good:

var $ul = $('<ul/>');
for (var i=0; i<100; i++) {
	$ul.append($("<li/>"));
}
$('html').append($ul);

Even if the parent element is already in the DOM, for extensive manipulations it is better to detach() it from the DOM, perform the manipulations, and then reattach it.

Source(s): [Artz], [Franko], [Irish], [LPRocksIT], [Osmani]

Rely on Event Delegation

Instead of attaching event handlers to individual elements, attach a single handler to a parent element and use the target property to determine the specific event target.

Bad:

$('li').on('click', function() {
	$(this).addClass('clicked');
});

Good:

$('ul').on('click', function(ev) {
	$(ev.target).addClass('clicked');
});

Source(s): [Artz], [Franko], [LPRocksIT], [Osmani]

Sources

  • [Artz] “jQuery Performance Rules”
  • [Buckler] “5 Tips for More Efficient jQuery Selectors”
  • [Didier] “jQuery Guide: 10 Best Practices with jQuery 1.7+ for Front-End Developers”
  • [Faeti] “jQuery Best Practices”
  • [Franko] “jQuery Best Practices”
  • [Irish] “10 Advanced jQuery Performance Tuning Tips from Paul Irish”
  • [Lal] “Best Practices for jQuery Developers”
  • [LPRocksIT] “JQuery Advanced - Performance Best Practices”
  • [Osmani] “jQuery Proven Performance Tips & Tricks”
  • [Way] “14 Helpful jQuery Tricks, Notes, and Best Practices”