RSS

Blog

jQuery: Inline caching for selectors

h328 May 2009 –  Comments (3)

Comments

jQuery used to have a cache, I cannot find it in the recent sources though.

$.ic('test', $(selector));
$.ic('test');

vs

var test = $(selector);
test

shorter and clearer and it has not advantages since you don't listen to DOM modification events (https://developer.mozilla.org/En/DOM_Events) to automatically invalidate your cache.

For the cache itself, I'd keep it inside jQuery; jQuery.cache = {}

What's the real benefits? The syntax isn't even better than doing it manually.

[] Yoan ~ 9 months, 2 weeks ago at 5:56 a.m.

The benefit is mostly that you can reuse $.ic('test'); anywhere in your code without resorting to a global variable.

Another use case would be for frequent selection of the same DOM elements that are not supposed to be modified.

I'm aware that this technique has a limited utility scope, that's why it probably won't make it to my jquery.utils library. It was mostly an exercise I wanted to do to see if this would be a viable technique and well, for fun.

PS: About the jQuery.cache idea, initially I used the window object. I'm not sure why, but noticed it took slightly longer to store and fetch in a external scope than when using this.

[] h3 ~ 9 months, 2 weeks ago at 8:24 a.m.
$.extend({ic: function(){ // [key, value, scope]
    var scope = arguments[2] || this;
    scope._ic = scope._ic || {};
    if (arguments.length == 1) {
        return this._ic[arguments[0]] || false;
    }
    else if (!arguments[1].jquery) {
        return scope._ic[arguments[0]] = arguments[1]; 
    }
    return scope._ic[arguments[0]] = arguments[1]; 
}});
[] Ben Atkin ~ 8 months ago at 3:01 p.m.

Copyrighted stuff .. u know.