JavaScript Tip: Image Preloading

Posted in JavaScript Tips
Tags: , ,

Pre-loading (caching) images is as easy as creating a new image object and setting the object’s src property.

But what if we have several images to load?

What makes this preloading is that you do it before you need to replace an image currently on the web page. One way to preload is to create an array at the beginning of a script containing the paths to all graphics you wish to preload, then loop through that list, creating a new image object for each one:

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 useful later on.

Leave a Reply

Your email address will not be published. Required fields are marked *