Forum Moderators: open

Message Too Old, No Replies

Pre-loading images

         

madk

4:59 pm on Sep 21, 2007 (gmt 0)

10+ Year Member



Hello all,

I'm trying to understand how to pre-load images for my rollovers and I can't find any good info.

So far I've got:


if (document.images)
{
preload_image = new Image(290,105);
preload_image.src="img/del_feature_2.jpg";
preload_image1 = new Image(290,105);
preload_image1.src="img/del_feature_1.jpg";
}

Now what I don't know if how to tell if this is working or not. I'm probably missing something here.

Dabrowski

5:21 pm on Sep 21, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That should work, you don't need to specify the sizes though, just use new Image();

You then need a function to flip the image, try this:

<p><a href='somewhere.htm' onmouseover='hover_preload()' onmouseout='unhover_preload()'><img id='image1' src='image1.jpg'></a></p> 

<p><a href='somewhere.htm' onmouseover='hover_notpreload()' onmouseout='unhover_notpreload()'><img id='image2' src='image2.jpg'></a></p>

For testing this it's probably better to use larger images that will take longer to load anyway, and a slow connection so you can see the difference.

That will give you some rollover-able images, note the event triggers in the <a> tags. Now you'll need image3 and image4 for the hover images, we'll flip 1 to 3 and 2 to 4.

Your script will look something like this.....


// Create and preload 1 image
var anImage = new Image();
anImage.src = "image3.jpg";

function hover_preload() {
var img = document.getElementById( "image1");
img.src = anImage.src;
}

function unhover_preload() {
var img = document.getElementById( "image1");
img.src = "image1.jpg";
}

function hover_notpreload() {
var img = document.getElementById( "image2");
img.src = "image4.jpg";
}

function unhover_notpreload() {
var img = document.getElementById( "image2");
img.src = "image2.jpg";
}

What we now have is 4 functions, a hover and a not, for each image. The first uses the preloaded image (anImage.src), and the other just loads the new image. As the original images are already loaded we don't need to preload these, just quoting the names will suffice.

If you spend more time on it you can cut it down to 1 function that does all images, and also remove the onmouse... from the tags. But that's another lesson.

Hope this works.