Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if image is fully loaded or NOT

I found this method below and it works fine in order to check if an image is fully loaded:

var myimg = new Image();
myimg.onload = function(){
alert("The image is now loaded");
}
myimg.src = "image url";

My question is:

How can I do an alert("The image couldn't be loaded") if, for some reason, the image couldn't be loaded or found (e.g., if the image URL is broken or even the image no longer exists from the provided image url)? Is there a way to solve this?

like image 481
Sam Avatar asked Dec 19 '12 01:12

Sam


People also ask

How do you know if an image is fully loaded?

The image is considered completely loaded if any of the following are true: Neither the src nor the srcset attribute is specified. The srcset attribute is absent and the src attribute, while specified, is the empty string ( "" ). The image resource has been fully fetched and has been queued for rendering/compositing.

How do you check if all images are loaded in jQuery?

In jQuery when you do this: $(function() { alert("DOM is loaded, but images not necessarily all loaded"); }); It waits for the DOM to load and executes your code. If all the images are not loaded then it still executes the code.


1 Answers

image nodes also allow for a DOM Level 1 onerror event handler.

myimg.onerror = function() {
};

If anything fails on loading or while loading an image, that handler will get executed. In addition to that, its not a bad idea at all to also check for the dimenions within the onload event

myimg.onload = function() {
    if( this.height && this.width ) {
    } else {
        // you might want to catch this case here too
    }
}
like image 160
jAndy Avatar answered Oct 07 '22 17:10

jAndy