If you deal with the same handfull of elements over and over again on the same page, doing those $('.class_name') selections can put a lot of load on the browser (especially IE). Here’s an easy way to cache those objects without doing any extra work:
var el_cache = {}; function e(a){ if(el_cache[a] != undefined) return el_cache[a]; el_cache[a] = $(a); return el_cache[a]; }
Then you would just change your jQuery calls from this:
$('.class')
to this:
e('.class')
Obviously there are more jQueryish ways of doing this but come on, you can’t beat that simplicity.
2 Responses
Leave a Reply
My name is Joey Nelson. I'm a web developer living in Raleigh, NC and working with Node.js, MongoDB, Ruby, PHP, jQuery and some other stuff. More about me.
Hi Joey,
It looks like pretty neat idea, but it would be great to see any performance tests based on this caching method.
How about
var e = (function() {
var cache = {};
return function (el) {
return (cache[el] = cache[el] || $(el));
}
}());