Preloading Images With Javascript
April 30th, 2008 | by Daniel |Every now and then I come across some topic which for some reason is like a black hole in the web. Sometimes I just find it impossible to find good information on a certain topic that I think would be quite popular. Last week I was asked to come up with an image crossfade/rotate script using Javascript. If you ask me, this would be much better handled by Flash but the requirement was quite strict.
Since I don’t really do much Javascript anymore I figured I’d try to look up some similar scripts online before I started, just to make sure I wasn’t wasting my time by doing something in a stupid way, etc. Though I spent quite a while searching I couldn’t find anything suitable, but I kept seeing people on forums or mailing lists asking how to preload images using Javascript. Again, lots of questions but not many answers. Preloading images means that your browser downloads them in the background while rendering the rest of the page, which is a nice feature in certain situations.
Here’s how to do it with some simple JS:
var image_path = 'images/'; var image_list = new Array(); // Define your list of images to be preloaded here... image_list[0] = 'IMG_0712.JPG'; image_list[1] = 'IMG_0713.JPG'; image_list[2] = 'IMG_0728.JPG'; image_list[3] = 'IMG_0757.JPG'; // This array will hold the actual image objects var image_array = new Array(); for(x = 0; x < image_list.length; x++) { // Create a new Image object and add it to our array... image_array[x] = new Image(); // Set the source attribute to point to your image. // This will trigger the preload. image_array[x].src = image_path + image_list[x]; }
See? Pretty easy. If you stick that simple JS into a blank HTML page your browser will load the images in the background and hold them in its memory until you choose to display them (instantly, since they are preloaded now) with some more JS code.
The image crossfade script that I wrote turned out to be more of a pain in the ass than anything and in the end wasn’t even required, but I’m going to try to wrap its functionality in an easy to use jQuery plugin in the next little while, and I’ll write here about how I did that. :)






