Full code - images.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JavaScript - preloading images</title>
<script type="text/javascript">
<!--
var myImages = new Array("image1.png", "image2.png");
var newImage = new Image();
for(i=0;i < myImages.length;i++)
…

Download the code »

Tutorial

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 preload 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.

Adobe Fireworks® Adobe Flash® and Adobe Photoshop® are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries.
MySQL is a registered trademark of MySQL AB in the United States, the European Union and other countries.
Copyright Pixelcode 2005 - 2010