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".
Written by Boopathi Rajaa
Related protips
4 Responses
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?
Good if your DOM don't change between two calls.
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) );
});
})();@mlb You have a point - this pattern is problematic with dynamic websites. But you could implement some cache invalidation for that.
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside