Image.onload event not firing

user3538389 picture user3538389 · May 30, 2014 · Viewed 10.4k times · Source

I'm trying to load a temporary image tag. Once that tag is done loading the image, I will set the 'src' for the img#main to the 'src' of the "temporary" image element. The thing is, the temporary image is successfully loading (it shows up on the screen), but the onload handler doesn't seem to fire. I never get my "Image is done loading" msg. I don't see how the temporary image can show up on the page, but not trigger its onload handler (would this happen if the browser is using a cached version of the image? But, I'm pretty sure I cleared the cache, anyway.). By the way, I've also tried code like B) below. But that didn't seem to work either. Also, I'm using Aptana Studio and loading my pages into my local WAMP server. I don't know if that makes any difference. Also, the urls that I'm assigning to the 'src' are document relative (like: "images/image_1.jpg").

I would appreciate any advice anyone might have. Thanks very much. Mike H.

A)

$('img#temp').load = function(){
  mch.say('Image is done loading');
}
$('img#temp').attr('src', url);
$('img#main').attr('src', url);

B)

var tempImage = new Image();
tempImage.src = url;
tempImage.onload = function(e){
mch.say("Image is done loading");
}

Answer

RienNeVaPlu͢s picture RienNeVaPlu͢s · May 30, 2014

There are two errors in A & B.

A) $('img#temp').load should be $('#temp').on('load') (if you're using jquery)

B) You should assign the onload event before assining the src.