View Full Version : Check if Image is Loaded?

04-08-2006, 05:20 AM
I've got a function that runs after an image is loaded. The only problem is, if the image is loaded already, the .onload doesn't register so the function doesn't run. Is there a way to check if the image is loaded already?

var img = new Image();
img.src = "http://example.net/picture.jpg";
img.onload = showImage;

04-08-2006, 08:53 AM
var img = new Image();
img.onload = showImage;
img.src = "http://example.net/picture.jpg";

04-10-2006, 03:00 AM

I should rephrase. Is there any way to determine whether or not the browser has cached an image? If not, is there any way to clear or destroy an image from the browser's cache?

I'm sure one doesn't have to actually access browser preferences to fool the browser into thinking an image isn't cached.

Upon further investigation, it seems my dilemma lies only in Safari. If the image is already loaded or in the cache, onload is ignored. Normally this wouldn't be that much of a problem, but my site needs to preload the images before they are displayed.

04-10-2006, 04:28 PM
I have done one thing to limit the problem, but it still can't be classified as a solution.

When an image is loaded, it adds the image name to an array. Every time it gets ready to load a new image, it checks to see if it's in the array first. If it is in the array, it skips the loading.

However, as the browser's cache is not cleared when the user exits the page, any visit after the first will result in an attempt to load the image again, which doesn't cause the function to be executed.

No ideas? Please?

04-10-2006, 11:49 PM
There are plenty of browsers out there that don't support image.onload at all so that code wont work there either. The only cross browser method I have found to test if an image is loaded is to test if the width or height of the image is greater than zero. If you set width and height in the HTML then you need to take a copy of the image and test that instead.

04-11-2006, 05:53 PM
This usually works, but you need a belt and suspenders:

var pic=new Image(x,y);//x,y is optional
pic.src= //path;

if(pic.complete) donePic()
else pic.onload= donePic;

The suspenders would be a timer that uses felgall's test

04-12-2006, 07:17 AM
Thank you, mrhoo!

That's awesome. Fixes a ton of problems and I haven't run into any browser incompatibility yet.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum