Preloading Images

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

Preloading Images

When working with files on a local machine, image rollovers like the ones we have seen in previous examples work just fine. However, when the user first hovers over a rollover image, the new image file has to be found and delivered to the page. The time it takes to load the image will depend on its size and the user's connection. It could take a few moments, causing an ugly pause in the rollover effect. This can be prevented by preloading images.

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:

<meta charset="UTF-8">
<title>Preloading Images</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">

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;
<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>

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 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();