Skip to content

Instantly share code, notes, and snippets.

@jduhls
Last active April 22, 2020 14:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jduhls/ceb7c5fdf2ae1fd2d613e1bab160e296 to your computer and use it in GitHub Desktop.
Save jduhls/ceb7c5fdf2ae1fd2d613e1bab160e296 to your computer and use it in GitHub Desktop.
jQuery.selectorCache (credit: https://ttmm.io/tech/selector-caching-jquery/)
/* Usage: $.selectorCache('#element')
* or to refresh cache: $.selectorCache('#element', true)
*
* Credit: https://ttmm.io/tech/selector-caching-jquery/
*/
(function($){
var debug = false;
function SelectorCache() {
var collection = {};
function getFromCache( selector, refresh ) {
if(undefined === refresh) refresh = false;
if (undefined === collection[ selector ] || refresh) {
collection[ selector ] = $( selector );
if (debug && window.console) window.console.log('Cache created for: ' + selector);
} else {
if(debug && collection[selector].length > 0) {
if (window.console) window.console.log('Cache hit for: ' + selector);
}
}
if(debug && collection[selector].length == 0){
if(window.console) window.console.log('Element does not exist: '+selector);
}
return collection[ selector ];
}
return { get: getFromCache };
}
var selectorCache = new SelectorCache();
$.selectorCache = function(selector, refresh) {
return selectorCache.get(selector, refresh);
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment