Skip to content

Instantly share code, notes, and snippets.

@gskema
Created October 16, 2016 12:58
Show Gist options
  • Save gskema/7232304d458ef628c4d17bac1e84a829 to your computer and use it in GitHub Desktop.
Save gskema/7232304d458ef628c4d17bac1e84a829 to your computer and use it in GitHub Desktop.
Cached jQuery .find and .closest methods. On repeated invokation, returns jQuery objects / DOM references from cache.
// jQuery warriors, assemble!
$.fn.cachedFind = function (selector) {
var cache = this.data('cached-find') || {};
if (undefined === cache[selector]) {
cache[selector] = this.find(selector);
this.data('cached-find', cache);
}
return cache[selector];
};
$.fn.cachedClosest = function (selector) {
var cache = this.data('cached-closest') || {};
if (undefined === cache[selector]) {
cache[selector] = this.closest(selector);
this.data('cached-closest', cache);
}
return cache[selector];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment