Of course, you need to cache DOM elements if necessary, regardless of whether you use jQuery or not.
But this question made me think that maybe we should have a plugin to help with this. I searched around and could not find it.
So, I wrote one very fast. This is the lazy jQuery selector loader ...
(function($){ var cachedObjects = new Array(); $.lazy = function(selector) { if (typeof selector != "string" || arguments.length > 1) return $.apply(this, arguments); var o = cachedObjects[selector]; if (o == undefined) { o = $(selector); cachedObjects[selector] = o; } return o; }; })(jQuery);
You would use it like that ...
$.lazy('.my-nav').show();
Let me know if I missed something. But I believe that it would be useful to use it when the elements you select are static and are never added or deleted dynamically.
UPDATE
I modified the code to make it more efficient. And I added the string to return $(selector)
when the selector is not a string. Thus, caching will only work when the selector is a string.
UPDATE # 2
Now it will be return $.apply(this, arguments)
when you are not just passing the string, for the jfriend00 clause.
source share