[thelist] determine when image has loaded

Jeff jeff at members.evolt.org
Mon, 29 Nov 1999 03:35:56 -0800


oliver,

:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
: From: Oliver Lineham <oliver@lineham.co.nz>
:
: Is it possible to determine when an image has loaded, using Javascript?
:
: This has various applications, but comes down to being able to tell when
an
: image has been cached and accessible by an object.
:
: foo = new Image;
: foo.src = "somefile.gif";
:
: That's fine, but can one determine when the image has actually been
downloaded?
:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

if you're just preloading images you're best just setting a variable
previous to the preload with a value of false and then change that to true
at the very end of the preloading.  this has worked for me a number of
times.

however, to answer your question directly there is a way to check that an
image has loaded.  you can either do it in the html, which won't really help
you here since they're being preloaded, or in the script itself, which is
what you'll want to do.  for learning sake, i'll mention how it's done in
html first.

an <img> tag has an onLoad event handler just like <body> and <frame>.  you
can call a function or set the value of a variable declared in the head of
your document.  be warned that this event will fire EVERY time the image
loads or you load a new image into that named <img> tag.  if you're going to
be using this particular to swap other images in and out it could get ugly.

the other way, the one you'll need to use, is to do it in the script.  you
can do this 2 ways, depending on what you're trying to accomplish.  you can
either use the onload event handler like this:

foo.onload = some_function;

or, you can checked the boolean value of "complete" property of the image
object, like this:

if(foo.complete)
{
  // evaluated to true
  // image loaded, let's
  // do something
}
else
{
  // evaluated to false
  // image not loaded
}

there are all kinds of other properties of the image object available as
well.  just check out the netscape developer docs for the scoop:

http://developer.netscape.com/docs/manuals/js/client/jsref/image.htm

i hope this helps.

good luck,

.jeff