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'];