Preload Images in an Array
8
snowdonkey
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.
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];
}
}






document.imageArray[i].src = "http://mysite.com/images/" + imageNames[i];