Last Updated: February 18, 2020
·
3.591K
· boopathi

jQuery caching

var $$ = (function() {
    var cache = {};
    return (function (selector) {
        return cache[selector] || ( cache[selector] = jQuery (selector) );
    });
})();
  • It's wasteful to constantly call $(selector) over and over again with the same selector.
  • Faster DOMElement look ups.

Update 1: Hide the cache variable inside a closure - as suggested by "dpashkevich".

4 Responses
Add your response

Simple but smart. I love it.

I particularly like that you don't have the overhead of pre-caching your selectors in separate variables at the top of your method, namespace, or constructor. Have you tried this in a project with Backbone? I typically cache my elements as properties of my View instances: myNavView.$nav = $('#nav'). That could simply become $$('#nav'), no?

over 1 year ago ·

Good if your DOM don't change between two calls.

over 1 year ago ·

Here's a modified version that hides the cache variable inside a closure:

var $$ = (function() {
    var cache = {};
    return (function (selector) {
        return cache[selector] || ( cache[selector] = jQuery (selector) );
    });
})();
over 1 year ago ·

@mlb You have a point - this pattern is problematic with dynamic websites. But you could implement some cache invalidation for that.

over 1 year ago ·