Last active
January 22, 2018 08:44
-
-
Save jtsternberg/14978579a9edf42ed069 to your computer and use it in GitHub Desktop.
jQuery selector cache with reset (original: http://eamann.com/tech/selector-caching-jquery/). If commenting, please ping me on Twitter, same username.
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
function Selector_Cache() { | |
var elementCache = {}; | |
var get_from_cache = function( selector, $ctxt, reset ) { | |
if ( 'boolean' === typeof $ctxt ) { | |
reset = $ctxt; | |
$ctxt = false; | |
} | |
var cacheKey = $ctxt ? $ctxt.selector + ' ' + selector : selector; | |
if ( undefined === elementCache[ cacheKey ] || reset ) { | |
elementCache[ cacheKey ] = $ctxt ? $ctxt.find( selector ) : jQuery( selector ); | |
} | |
return elementCache[ cacheKey ]; | |
}; | |
get_from_cache.elementCache = elementCache; | |
return get_from_cache; | |
} | |
var cache = new Selector_Cache(); | |
// get selector | |
cache( '#selector' ); | |
// get selector and reset cache | |
cache( '#selector', true ); | |
// get selector with $context | |
cache( 'img', cache( '#selector' ) ); | |
// get selector with $context, and reset | |
cache( 'img', cache( '#selector' ), true ); | |
// get selector with $context, and reset both selector and $context (whoa) | |
cache( 'img', cache( '#selector', true ), true ); | |
// Manually add a selector | |
cache.elementCache['#another-id'] = jQuery( document.getElementById( 'another-id' ) ); | |
// Then use it: | |
cache( '#another-id' ); |
I have the same problem as @bradyvercher. If context is a simple jQuery selector like $( '#container' )
then it's good. But if it's complicated like $( '#container' ).next()
then the code that retrieves context's key won't work reliably.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@afanjul updated, thanks!
@mecklund, see if the changes made based on @afanjul's suggestion resolve your issue.