Home » Internet » Web Designing » How to preload images with JavaScript

How to preload images with JavaScript



It makes sense to preload images with JavaScript for neat mouseover and rollover effects or if you need a particular set of images to load first before proceeding further, for instance, showing a smooth slideshow. You also need to preload images when you expect your visitors to have a slower net connection but you need all the images for the user interface. It might take a longer time to load a particular page, but at least they will get everything working.

With JavaScript you can preload one image at a time or you can preload an entire set of images. Let’s first see how you can preload just a single image.

<script language=”javascript”>
        var loadthisimage = new Image();
        loadthisimage.src=”theimagename.jpg”;
</script>

You see? It’s very simply to preload a single image with JavaScript. But what if you have a bunch of images to preload? You can store the names of the images in a JavaScript array and then loop through that array to preload all the images. This is how you can do it:

<script language=”javascript”>
        var imageObject = new Image();
        var images = new Array();
        images[0] = “image1.jpg”;
        images[1] = “image2.jpg”;
        images[2] = “images3.jpg”;
        images[3] = “images4.jpg”;
        images[4] = “images5.jpg”;
        for(i=0; i<4; i )
        {
                imageObject.src = images[i];
        }
</script>

As you can see, in order to preload all the images they are first stored in a JavaScript array and then preloaded by executing a for loop.