May 2012

Lazy Loading jQuery Selector

by Steve Wortham
I had this thought today when I was reading a question on StackOverflow. The question was about the performance advantage of caching your DOM elements found with jQuery.

So what if jQuery had a mechanism for lazy loading DOM objects?

I mean, as it stands, every time you use a jQuery selector it's crawling the DOM to find elements.  So it's wise to cache those results when appropriate.

Or if you know you're dealing with static page elements then you can just use this handy plugin I created...

(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);


Then you'd use it like this...

$.lazy(".BestSellers").show();


This will cache the results internally after the first call. As a result, jQuery doesn't have to work so hard to crawl the DOM with every call to this selector. This should actually speed up the page. Most of the time the performance advantage here won't be noticeable unless you're dealing with a very large page. Still, I thought this was a neat way of handling the problem without completely refactoring your code.



comments powered by Disqus