Painless JavaScript lazy loading with LazyLoad

Update: There’s a newer version of LazyLoad now. You should use it instead of the version described in this post.

With all the fancy JavaScript libraries to choose from these days, it can be hard to keep your website’s page weight down. Even if you’re using a small, sleek library like YUI or MooTools, there are often times when it would be nice to be able to load certain scripts only when they’re needed.

For example, if you load a bunch of fancy animation libraries to do something spiffy when the user clicks a button, but then the user does something else instead of clicking the button, then you’ve wasted precious time loading scripts you didn’t even need.

Lazy loading is when you wait to load something until you actually need it. It’s not a new concept, and the techniques for implementing lazy loading in JavaScript have been around for a while, but it can be a real pain in the ass to roll your own lazy loading solution, especially if you want it to be compatible with all the major browsers.

Luckily, I’ve done the hard work for you. All you need to do is include LazyLoad in any web page like so:

<script src=""></script>

Then, when you need to load a script, call LazyLoad.load() or LazyLoad.loadOnce() and pass in the URL of the script you want to load (or an array of URLs if you need to load multiple scripts). You can also specify a callback function that will be executed when the scripts are finished loading.

The only difference between LazyLoad.load() and LazyLoad.loadOnce() is that loadOnce() checks to see if the scripts have already been loaded and makes sure nothing gets loaded twice.

// Called when all scripts have finished loading.
function loadComplete() {
  alert('Hooray for LazyLoad!');

// Load the YUI Dom, Event, and Animation libraries if they haven't already
// been loaded.
], loadComplete);

If necessary, you can also have LazyLoad pass an argument to the callback function or execute the callback in a specific scope:

// Pass an argument to the callback function.
LazyLoad.load('', loadComplete, 'custom argument');

// Execute the callback function in the specified context.
LazyLoad.load('', loadComplete, this, true);

For more usage details, see the source documentation or the unminified source code.

If you’d like to use LazyLoad, you can either include it directly from my server as demonstrated above, or you can download it and host it yourself:

LazyLoad works in Firefox 2+, IE6+, Chrome, Safari 3+ (including iPhone) and Opera 9+. If you run into any problems, please let me know.