Preload Images

Preload Images


Sometimes images can be a bit large in memory size. Having a rollover effect work efficiently means it should work properly from the start of the page being loaded. Without a preload, there may be a short delay in the rollover effect at first since the browser will only download images as they become "active" or displayed. The secondary (or rollover image) is not active until the OnMouseover event happens. Thus, a pause is created to see the effect as the second image takes time to download.

So... we have to create a small script to activate the image which will place it into the browsers cache memory for later use. The cache (pronounced cash) is the browser's temporary storage memory for pages and images it comes across on the internet. Has the second or third visit to any web page loaded much faster for you than your first visit? That is because the browser is showing your images or pages it already has in its memory. Putting these rollover images into the cache will "force" them into memory before they are even seen by the browser.

  • PreImage1 is just a variable being used for this process. Any variable name can be used here.
  • new Image() tells the script to prepare to use an image in some way. The numbers are the width and height of the image being loaded. You can leave this area blank, but it always helps a bit to have them in there.
  • PreImage1.src loads the specified image into the variable area.

Here is a small example if you have more than one image to preload. I've added a second image for preloading. Notice the differences and similarities between the two examples.

Another way of preloading images is to place them into an array. You may want to freshen you knowledge on javascript arrays here.

First, look at the last part of that script. preloading holds the src (source) values for all the images you want to have preloaded. It is a call that sends those values to the function part.

Now go from the top of the script. myimages is a temporary array created for the purpose of preloading these images. preloading is the function where all the preloading is happening. x is being used as a counter in a for loop. The loop will keep going until x becomes greater than the number of image values. The number of image values is calculated by using arguments.length.

The main part of the for loop is very similar to the previous preload examples. The only difference is the addition of the array counter.

This version of the preload is usually much nicer to use when a large number of images have to be preloaded.

Table of Contents

Rollover / Image Swap