Preload your Images with this FREE jQuery plugin!

24 May 2009 Ferado

I like you. I think you’re cool. Thank you for reading my Blog. It’s getting better the more I write. But anyway, enough about us. Let’s talk about how you’re going to use my Image Preloader script. It’s free, do whatever you want with it. Call it your own, whatever, I don’t really care. I like FREE knowledge. I love to compete. I love it when I’ve worked so hard that I can’t think anymore.

I digress.

I wanted to share with you all a way to preload your images with jQuery. If you don’t know what jQuery is, you’re living in the stone age of the web. jQuery makes the average developer look like a Rockstar. I’m not even kidding. Please, read up on jQuery. I’m a firm believer that no site should be built without jQuery at its core.

Now, here’s how you can make yourself an image preloader with jQuery, or well, it’s how you preload your images with jQuery. Okay? We on the same page here?

The code:
[cc lang=”javascript”]
jQuery.preload_images = function() {
for(var i = 0; i < arguments.length; i++) { jQuery("“).attr(“src”, arguments[i]);
}
};
[/cc]

The minified verision:
[cc lang=”javascript”]
jQuery.preload_images=function(){for(var i=0;i“).attr(“src”,arguments[i]);}};
[/cc]

Here’s how you would use it in your code:
1. Include the plugin
2. Place the following snippet in an external file or in between “script” tags:
[cc lang=”javascript”]
$.preload_images(“images/something.gif”, “images/somethingelse.jpg”, “images/etc.png”);
[/cc]

You can also use it to load just one image:

[cc lang=”javascript”]
$.preload_images(“images/something.gif”);
[/cc]

Add as many images as you want to it. However, if you really have to load that many images, you really should re-think your site design. I think preloading your images is a little old school. I only use the preceding code when I’m working with a design already in place or a photo gallery. And usually, with photo galleries, they preload the images anyway. This is more of a nice to have function. I actually put it in my toolbox for rainy days. Why? Because I grew up a boyscout and I like to be prepared.

Don’t worry, you don’t have to copy and paste if you don’t want to. I’ve provided the following downloads for your convenience:

Easy to read version:
DOWNLOAD SOURCE CODE

Minified version:
DOWNLOAD SOURCE CODE