gzstgq
Last Updated: February 25, 2016
·
1.284K
· boopathi
Cover

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".

Say Thanks
Respond

5 Responses
Add your response

2304
309686 10150358450866411 5102478 n small

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 ·
2312
81829def637962204635704c091036ea

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

over 1 year ago ·
2322
D42a7264714dee5006b9c99d2567a320

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 ·
2381
Bae16dbfb2dcfb36d3d9bb9bce7bf3db

@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 ·
15568
Dac8182499d9d16703b52d653806840b

I created a simple plugin a little while ago which should do the job:
https://github.com/Lugat/DOMCache/blob/master/DOMCache-0.1.js

over 1 year ago ·