Preloading images in Javascript
We firstly need to list the images that need to be preloaded.
var myImages = new Array("image1.png", "image2.png");
In this example we have listed the images in an array. We now need to go through the array and load the images.
The Image object
We will pre-load the images by using the Image object.
var newImage = new Image();
Finally we need to change the src
attribute of the Image object to load the images in the background.
for(i=0;i < myImages.length;i++)
{
newImage.src = myImages[i];
}
When the image object gets a new src
value it loads the image, so by changing the src
value to a list of images they are all loaded.