HTML and CSS Reference
In-Depth Information
12.3.2 Preloading Images and the Image() Constructor
If you assign a new image to the src property of an image object, there might be some lag
in the time it takes to download the image from the server. And if you have a slow con-
nection, this can be a real turnoff, to the point that you don't even bother to wait for the
image to load. To solve this problem, the Image() constructor allows you to preload an
offline image; this puts the image in the browser's cache before it is used. This technique
of caching the image makes the response time much faster, especially when you have
large images, animation, rollovers, and the like. The Image() constructor can also define
the size (height and width, in pixels) of the cached image. Be sure to put the Image()
constructor in the <head> portion of the document so that the images are put in the
cache before the script starts to run. For seamless transition when replacing one image
with another, both images should be of the same size, accomplished by cropping or scal-
ing the image. To use the Image() constructor, see next.
var newImage = new Image();
var newImage = new Image(height, width)
newImage.src = "image.gif";
var myImage = new Image(200,300);
myImage.src = "baby.gif";
It is possible, but unlikely, the viewer is using a browser that doesn't support the
image object. We can add a little snippet of code to detect if the image object exists and
then continue with preloading the images:
if(document.images) {
pic1=new Image(100,25);
A Simple Rollover with a Mouse Event. We talked about event handlers with the
form object and now we will demonstrate the use of an event handler with the image
object. For a complete discussion, see Chapter 13. The objective of the next example is
to change the image when the mouse rolls over a link, and to change it back when the
mouse moves away from the link. There are two images involved: the image that initially
appears on the page and the image that replaces it when the mouse rolls over the link
associated with it. Both of the images are preloaded with the Image() constructor. The
JavaScript onMouseOver event is triggered when the user's mouse moves onto the link,
and the onMouseOut event is triggered when the mouse moves away from the link.
Search WWH ::

Custom Search