Last active
April 22, 2020 14:41
-
-
Save jduhls/ceb7c5fdf2ae1fd2d613e1bab160e296 to your computer and use it in GitHub Desktop.
jQuery.selectorCache (credit: https://ttmm.io/tech/selector-caching-jquery/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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