Electric Type

Multimedia

About Us

News

Help

Advanced JavaScript Tutorial
Lesson 4

by Thau!

Page 4 — Preloading Images — How's It Done?

It's not terribly hard to preload your images. All you have to do is create a new Image object, then assign the image to preload to the src of that image Just like so:
var an_image = new Image();
an_image.src = "my_nice_image.gif";
Setting the .src of the new image automatically downloads the image to the user's hard drive, assuming, of course, the cache is turned on. The image is read off the hard drive, instead of downloaded.

Try mousing over the links below. The image swap should happen pretty quickly.


one
two
three

The only thing left is to learn how to make the preload happen when the page first loads in the browser, before any rollover action. Happily, this is pretty straightforward. The body tag has an event handler called onLoad, which is called once a page finishes loading. If you have a body tag that looks like this:

<body onLoad="doPreload();">
The doPreload() function will be called when the page is done loading. The code for the functions that do the loading looks like this:
function doPreload()
{

   var the_images = new Array('stuff3a/kwmatt.jpg','stuff3a/matbon.jpg',
   'stuff3a/lunchMat.jpg');
   preloadImages(the_images);
}

function preloadImages(the_images_array) {

   for(var loop = 0; loop < the_images_array.length; loop++)
	
   {
 	var an_image = new Image();
	an_image.src = the_images_array[loop];
   }
}

Because I put that onLoad event handler in the body tag, the function doPreload() gets called when the page finishes loading. doPreload() creates an array of the names of images to preload and passes that array to preloadImages(), which loops through the array. With each pass through the loop, it creates a new Image object and assigns an image to the src of that image object.

Not too hard, hmm? That Image object is pretty useful, right? I'm glad you think so, because now it's time to move on to some mind-blowing — and trickier — things. Take a break now, because on the next page we're going to enter the wide world of object creation.

next page»


Tutorials  

User Blogs  

Teaching Tools  

Authoring  

Design  

Programming help  

Advanced Flash  

Javascript  

Glossary  

PHP Coding  

User Blogs

Screen Shots

Latest Updates

Contact Us

Valid HTML 4.01!
Valid CSS!

Breadcrumb

© ElectricType
Maintained by My-Hosts.com
Site map | Copyright | Disclaimer
Privacy policy | Acceptable Use Policy
Legal information.