Using Javascript To Switch Images

This post isn’t really going to be about javascript rollovers, as they have been covered in the past and really are at the point where CSS has basically replaced them. This post is actually going to briefly explain how to preload an image with javascript, then add it to the page (either as a new image or replacing an existing image).

Let’s say you have a page with multiple thumbnails that can be clicked to load the full-sized image in a specific area of the page. In the old days, we would have done this in one of two ways: 1) Make the link actually lead to a different page with that new image shown or 2) Load all of the images at once, hiding them with CSS, slowing down the initial load time of the page.

With the Javascript image() object, however, you can actually preload the images when the appropriate thumbnail is clicked or even after the page finishes loading. You can even display a “loading” indicator until the new image is fully loaded.