jQuery DOM cache object

The first problem with jQuery is uncached queries. Instead of doing something like:

$('h1').addClass('inactive');
$('h1').text('hello');
$('h1').animate({height: "100px"});

You have to do that:

var $h1 = $('h1');

$h1.addClass('inactive');
$h1.text('hello');
$h1.animate({height: "100px"});

Because the h1 is just fetched once in the DOM. This is faster. Sometimes you will reuse this same h1 in another function. So you have to re-declare the $h1 variable, and it’s not optimised.

Instead, you can do a global approach for caching DOM object from jQuery: Create a global object with the selector as key and DOM object as value. This is an implementation:

DOMCACHESTORE = {};
DOMCACHE = {
get: function(selector, force) {
if (DOMCACHESTORE[selector] !== undefined && force === undefined) {
return DOMCACHESTORE[selector];
}
DOMCACHESTORE[selector] = $(selector);
return DOMCACHESTORE[selector];
}
};

Or

$C = (function($) {
var DOMCACHESTORE = {};
return function(selector, force) {
if (DOMCACHESTORE[selector] === undefined || force)
DOMCACHESTORE[selector] = $(selector);
return DOMCACHESTORE[selector];
}
})($);

How to use it?

DOMCACHE.get('h2').addClass('super');
// Later:
DOMCACHE.get('h2').removeClass('super');

This DOMCACHE.get('h2') will be the same, and it will just be fetched once. If you have new h2 on the page, added by JavaScript, you can force the re-fetch:

DOMCACHE.get('h2', true).addClass('super');
// Now, we have all h2:
DOMCACHE.get('h2').addClass('all');

It’s a very simple trick for better performance on your jQuery code. Any suggestions or bugs? Let me know.