Preloading Images

Contact Us or call 1-877-932-8228
Preloading Images

Preloading Images

When using JavaScript to dynamically load an image, perhaps in response to some user interaction, preloading the image (the image not initially showing on the screen) can eliminate a delay in the image appearing for the user. Images can be preloaded by creating an Image object with JavaScript and assigning a value to the src of that Image. A sample is shown below:

Code Sample:

ImagesWindowsTimers/Demos/PreloadingImages.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Preloading Images</title>
<link href="style.css" rel="stylesheet">
<script>

var imagePaths = [];
imagePaths[0] = "Images/Hulk.jpg";
imagePaths[1] = "Images/Batman.jpg";

var imageCache = [];

for (var i=0; i<imagePaths.length; i++) {
	imageCache[i] = new Image();
	imageCache[i].src = imagePaths[i];
}

function imageRollover(img, imgSrc) {
	img.src = imgSrc;
}
</script>
</head>
<body>
<div style="text-align:center;">
<h1>Simple Image Rollover Function</h1>
<img name="Banner" src="Images/Banner.jpg"
	onmouseover="imageRollover(this, 'Images/Hulk.jpg');"
	onmouseout="imageRollover(this, 'Images/Banner.jpg');">
<img name="Bruce" src="Images/Bruce.jpg"
	onmouseover="imageRollover(this, 'Images/Batman.jpg');"
	onmouseout="imageRollover(this, 'Images/Bruce.jpg');">
<p>Who are you calling simple?</p>
</div>
</body>
</html>

Code Explanation

Notice that the code is not in a function. It starts working immediately as follows:

  1. An array called imagePaths is created to hold the paths to the images that need to be preloaded.
    var imagePaths = [];
  2. An array element is added for each image to be preloaded.
    imagePaths[0] = "Images/Hulk.jpg"; imagePaths[1] = "Images/Batman.jpg";
  3. An array called imageCache is created to hold the Image objects that will hold the preloaded images.
    var imageCache = [];
  4. A for loop is used to create an Image object and load in an image for each image path in imagePaths.
    for (var i=0; i<imagePaths.length; i++) { imageCache[i] = new Image(); imageCache[i].src = imagePaths[i]; }
Next