Preload Images in an Array





8
Date Submitted Sun. Aug. 13th, 2006 2:23 PM
Revision 1 of 1
Helper snowdonkey
Tags "array" | "images" | "javascript" "preload"
Comments 1 comments
Load images more quickly in a web page by having the browser cache them before they are requested by the user.

This script specifies the location of images that share a common folder. It can be used for multiple images and folders.

This method uses less code and is more maintanable than specifying the location of each image individually.

//Store the image names in an array
var imageNames = new Array("cat.jpg", "dog.gif", "moose.png");

//Pass the array to the function that will preload them
preloadImages(imageNames);

function preloadImages(imageNames)
{
        //Create an Array object that will hold each image's name and location
        document.imageArray = new Array;

        //Loop through the image names
        for(var i = 0; i < imageNames.length; i++)
        {
                //Create an Image object for the particular image name
                document.imageArray[i] = new Image;

                //Specify the Image object's folder location
                document.imageArray[i].src = "http://mysite.com/images" + imageNames[i];
        }
}
 

Bennett Joseph

Comments

Comments Snippet Revision
Sun. Aug. 13th, 2006 9:37 PM    Helper snowdonkey

Voting