Skip to content

Instantly share code, notes, and snippets.

@cuth
Last active January 11, 2016 15:16
Show Gist options
  • Save cuth/22b60aad4d3f9f12d958 to your computer and use it in GitHub Desktop.
Save cuth/22b60aad4d3f9f12d958 to your computer and use it in GitHub Desktop.
Cache any jQuery selector with $.stash
(function ($) {
'use strict';
var cache = {};
$.stash = function (selector) {
if (!selector) {
return cache;
}
if (typeof selector !== 'string' || arguments.length > 1) {
return $.apply(this, arguments);
}
if (cache.hasOwnProperty(selector)) {
return cache[selector];
}
return (cache[selector] = $(selector));
};
}(jQuery));
'use strict';
const $ = require('jquery');
const cache = {};
module.exports = function (selector) {
if (!selector) {
return cache;
}
if (typeof selector !== 'string' || arguments.length > 1) {
return $.apply(this, arguments);
}
if (cache.hasOwnProperty(selector)) {
return cache[selector];
}
return (cache[selector] = $(selector));
};

jquery.stash

Easily cache a jQuery selector to improve performance when reusing the same selector. Caching is only supported on strings and does not support the context argument.

Poor jQuery example:

$('.select li').html('test');
$('.select li').empty();

This is a common jQuery performance mistake. jQuery doesn't know if any li elements have been added or removed from .select so the second time $('.select li') is called it needs to do the same DOM lookup for those elements.

But in some cases we know that those elements will never change so we save the jQuery selector in a variable.

var $selectLi = $('.select li');
$selectLi.html('test');
$selectLi.empty();

With Stash you can just use .stash() to call your selector.

Stash example:

$.stash('.select li').html('test');
$.stash('.select li').empty();

Use stash with no arguments to return the cache object.

console.log($.stash()); // [cache object]

Stash is ment to be used on "immutable" elements but if you need to refresh the selector you can delete a selector from the cache.

delete $.stash()['.select li'];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment