Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jtsternberg
Last active May 19, 2020 04:14
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtsternberg/1e03f5fd5be8427170c5 to your computer and use it in GitHub Desktop.
Save jtsternberg/1e03f5fd5be8427170c5 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.
function Selector_Cache() {
var collection = {};
function get_from_cache( selector, reset ) {
if ( undefined === collection[ selector ] || true === reset ) {
collection[ selector ] = jQuery( selector );
}
return collection[ selector ];
}
return { get: get_from_cache };
}
var cache = new Selector_Cache();
// get selector
cache.get( '#selector' );
// get selector and reset cache
cache.get( '#selector', true );
@jtsternberg
Copy link
Author

Improved version which can take a second 'context' parameter (like the jQuery selector can): https://gist.github.com/jtsternberg/14978579a9edf42ed069

this way you can use your cached parent selectors to find a child element.

I'll probably just replace the contents of this gist w/ that one.

@adampasz
Copy link

adampasz commented Apr 1, 2015

Thanks for sharing this. Saved me some time. :)
It might be useful to have a way to flush the entire cache as well...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment