Image.onload event not firing
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
.
user3538389
Updated on June 04, 2022Comments
-
user3538389 about 2 years
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"); }
-
user3538389 about 10 yearsI believe jquery uses .load() if I'm not mistaken. Your right about the source order. I just typed it wrong in the question.
-
RienNeVaPlu͢s about 10 years@user3538389
.load()
is used by jquery to load data from a server, but you want to catch theonload
event, which can be done withon('load')
(edited the answer). And here's a fiddle. -
user3538389 about 10 yearsOh, right. I thought load() was a shortcut fn for .on("load", handler). Stupid mistake.
-
HartleySan about 9 yearsPoint B here helped me resolve a similar problem I was having in which images were cached, and as a result, sometimes, an image would be already completely loaded before the onload event even got set up, thus causing processing I wanted to be performed in the onload event callback for each image to not be performed for some images. Thanks.