How to Preload Images

"Preloading" loads an image file into the users' computer memory so that it can be instantly accessed when needed. This is useful, for example, if you have a mouseover event and an image needs to change without any delay.

Option 1: Nice and Simple

To preload an image into your web page, paste the code below into the document head (replace the red image file name with your own):

<script type="text/javascript">
if (document.images) {
    img1 = new Image();
    img1.src = "image.jpg";
}
</script>

You can add more images by duplicating the image lines, e.g.:

<script type="text/javascript">
if (document.images) {
    img1 = new Image();
    img1.src = "image.jpg";
    img2 = new Image();
    img2.src = "image2.jpg";
}
</script>

Option 2: A Flexible Array

This method can be used if you have an external JavaScript file that is used by multiple pages. Use the same function to easily preload any number of images on different pages. Firstly, add the following function to your main JavaScript file:

function preload(images) {
    if (document.images) {
        var i = 0;
        var imageArray = new Array();
        imageArray = images.split(',');
        var imageObj = new Image();
        for(i=0; i<=imageArray.length-1; i++) {
            //document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
            imageObj.src=imageArray[i];
        }
    }
}

Then in the <head> of each web page, add the following code after you've called the main JavaScript file:

<script type="text/javascript">
preload('image1.jpg,image2.jpg,image3.jpg');
</script>

Replace the file names in red with your own files. You can have as many as you like, just make sure that they are separated by a comma.

Option 3: No JavaScript

You can also preload an image without JavaScript by creating a 1 pixel square version of the file and hiding it somewhere on the page, like so:

<image src="picture.jpg" width="1" height="1" border="0">