View Full Version : how to test an image download?

DHTML Kitchen
05-27-2005, 03:06 AM
I know bc was working on something like this a while back. I just need simple
isImageOK function. returns true if status is 200, 302, 304, et c, but NOT 500, 404.

Basically, isImageOK.

var x = new Image();
x.src = "http://www.google.com/intl/en/images/logo.gif"
x.onerror = function(e) { document.title = e };

Mozilla fires onerror when the domain is not trusted. For example: when you're at smarty.php.net and and a script called a new Image from google.com, onerror would fire for mozilla and onload would not fire. Damn, I have no idea why.

Is there an easy way to tell if an image has loaded?

Willy Duitt
05-27-2005, 04:26 AM
Try using: complete

Harry Armadillo
05-27-2005, 05:03 AM
In Gecko-browsers, complete only tells you if the loading-phase is finished, not whether it was successful (the existence of non-zero naturalWidth and naturalHeight are good indicator of success).

DHTML Kitchen, I've had no problems with onerror and onload for images in Moz and Firefox, on-site or off-. Perhaps you could show us more of your code? One thing that can cause problems is assigning the src before assigning onerror and onload -- the image may load/error before the handler exists.

FWIW, this behaves as I'd expect on Moz 1.7 and Firefox 1.0.4
var x = new Image();
x.onerror = function(e){alert('Error: '+this.src+'!\ncomplete is '+this.complete.toString())};
x.onload = function(e){alert(this.src+' loaded!\ncomplete is '+this.complete.toString())};
x.src = "http://www.codingforums.com/logo.gif";

var y = new Image();
y.onerror = function(e){alert('Error: '+this.src+'!\ncomplete is '+this.complete.toString())};
y.onload = function(e){alert(this.src+' loaded!\ncomplete is '+this.complete.toString())};
y.src = "http://www.codingforums.com/blah.gif";