I am attempting to use jQuery to determine if an image has properly loaded.
The following works just fine (and returns true
or false
as of
Jquery makes it really simple.
You can just use the .load() function to bind an event for the time when image is completely loaded.
$("img").load(function() {
// Yeay, it was loaded, and works in all browsers!
});
myimage=new Image();
myimage.src="whatever";
if(myimage.height>0 && myimage.complete){alert("my image has loaded");}
// might be overly simple but works for me in all browsers i think.
You can use load() but beware of Internet Explorer: It won't fire the event, if the image is cached
if($img[0].readyState === 4){ // image is cached in IE
alert("Image loaded!");
}else{
$img.load(function(){ // for other browsers and IE, if not cached
alert("Image loaded!");
});
}
I dont know if firefox has another prop, method that does it but, you can use this workaround:
$(document).ready(function(){
$("img").each(
//for each image declared in html
function(index)
{
document.images[index].complete= false;
document.images[index].onload = function(){ this.complete= true};
});
});
Yes, I was just working on an AJAX page that dynamically loaded images. I also wanted to detect if images were loaded so I could transition them in with a jQuery effect.
img = $('myImageID')
img[0].src = 'http://new.url.for.image/';
alert(img[0].complete); // seems to always return true
// in Firefox, perhaps because
// the original src had been loaded
So instead I had to do this...
img = $('myImageID')
newImg = $('<img>') // create a completely new IMG element
.attr('src', 'http://new.url.for.image/')
.attr('id', img[0].id);
img.replaceWith(newImg);
img = newImg;
alert(img[0].complete);
(Note: I haven't tested this exact code, it's a simplified version of what I was trying to do, but hopefully communicates the idea.)
Simon.
In my case, I use the method
document.images['XXX'].addEventListener('load', dealJob(), false);
and in function dealJob, I use document.images['XXX'].complete to check the image, but it always returns true.
When I change to use the method
document.images['XXX'].onload = function() {dealJob();}
and in function dealJob, the result of document.images['XXX'].complete is correct.
Maybe it can help you.