Cache your selectors with this jQuery plugin

We’ll look into the jQuery Selector Cache Plugin to see how you can use it to cache jQuery objects.

jQuery Selector Cache is a simple plugin that lets you query elements in the same way you would by using $() except with an additional caching mechanism.

Instead of $(".row") you use $.q(".row").

The selector will be cached the first time you query it and on subsequent calls it will be retrieved directly from the cache avoiding unnecessary lookups.

It was inspired by Justin Sternberg’s $-cache-with-find.js.

Why would you use it?

Because selector lookup can be expensive and you should only do it the first time or when the DOM changes.

Normally you would use helper variables, but by tying it to jQuery you get a global cache.

How to

Besides using $.q(selector) to get elements you can also pass the context as a second argument:

$.q(selector, context);

Force a cache refresh by using a boolean in the second or third argument:

$.q(selector, true);
$.q(selector, context, true);

You can also access the cache directly to reset it or manually update it:

// clear cache
$.selectorCache = {};

// manually update cache
$.selectorCache[selector] = $(selector);

More details

Check the repository on GitHub to get the source code and for more details.

Nuno Freitas
Posted by Nuno Freitas on August 27, 2015

Related articles