February 27, 2006
Image Preloading
In our recent January meeting I showed you how to work with the Image object and create some simple "roll-over" effects with a new image appearing after the user "rolls" their mouse over the area. Also accompanying this technique is preloading (caching) all images that will be used before hand so the effect looks immediate instead of waiting for the new image to load.
The code for this was:
var img = new Image(); img.src = 'image1.gif';
But what if we have several images to load?
Apart from repeating those lines of code for each image, a more efficient way to load multiple images would be to use a for loop.
var imgName = ['image1', 'image2', 'image3', 'image4']; var imgObjects = []; for (var i = 0l i < imgNames.length; i++) { imgObjects[i] = new Image(); imgObjects[i].src = imgNames[i] + '.gif'; }
If all the images are the same type (.gif) you can add the extention at the end otherwise you would put the extension name in the imgNames array itself.
Notice that the code is storing each Image object to an array as we go along, rather than reusing the same reference for each iteration. It's done because image loading is asynchronous (the load request is made, but the script carries on without waiting).
If we reused a single variable for all iterations, we could end up storing only the final image in the cache, as each request would be overwritten by the next. We avoid this possiblity by using an array to save the images --- we have a unique reference for each image, so the time and order in which they're loaded doesn't matter.
This solution also provides a convenient set of references to our cached Image objects, which could be userful later on.
