tckmn
tckmn

Reputation: 59273

Checking if an image is loaded, cross browser

I need a cross browser solution to find if an image is done loading.

I know about this:

var theImage = new Image()
theImage.src = 'http://pieisgood.org/images/slice.jpg' //yum, pie :)
//later...
if (theImage.complete) {
    //do stuff
}

Is that cross browser compatible (by that I mean FF, Chrome, Safari, Opera, IE8+)? If not, how can I do this in a cross browser and jQuery-less way?

Upvotes: 2

Views: 1207

Answers (3)

Fernando Jorge Mota
Fernando Jorge Mota

Reputation: 1554

Something as:

var theImage = new Image()
theImage.src = 'http://pieisgood.org/images/slice.jpg' //yum, pie :)
theImage.isLoaded = false;
//later...
theImage.onload = function(){
    theImage.isLoaded = true;
    //do stuff
}
if(theImage.isLoaded){
    alert("Loaded");
}
document.body.appendChild(theImage); // VERY needed

Should work.

Just as it set attributes as the image is really loaded. :)

Upvotes: 4

Ol Sen
Ol Sen

Reputation: 3348

or just control it via html and call your function on specified img onload event

<img src="whatever.png" onload="dostuff()" />

Upvotes: 1

vishakvkt
vishakvkt

Reputation: 864

I think you can use the 'onload' event.

image.onload = function() {
};

This should be bound though, before you set the 'src' of the image.

Upvotes: 2

Related Questions