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?
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.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With