Skip to content

Instantly share code, notes, and snippets.

@pseudosavant
Last active March 30, 2016 21:44
Show Gist options
  • Save pseudosavant/8720377 to your computer and use it in GitHub Desktop.
Save pseudosavant/8720377 to your computer and use it in GitHub Desktop.
Automatically cache your DOM queries using a wrapper function like this.
// jQuery wrapper
var cacheQuery = function(query) {
this.cache = this.cache || {};
if (!this.cache[query]) {
this.cache[query] = jQuery(query);
}
return this.cache[query];
};
// DOM wrapper
var cacheQuery = function(query) {
this.cache = this.cache || {};
if (!this.cache[query]) {
this.cache[query] = document.querySelectorAll(query);
}
return this.cache[query];
};
// Example
cacheQuery('.myForm input[type=submit]').val('Processing'); // Returns `DOMElement` or a jQuery object after a lookup
cacheQuery('.myForm input[type=submit]').attr('disabled', true); // Returns same `DOMElement` or jQuery object but without doing a lookup
@Kurniawandering
Copy link

This piece of code can't work, I assume you nee to use the constructor.

Or maybe I'm looking at the wrong way, then please explain how 'this' could work according to your function?

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