Fallback mechanism when img src is invalid
Hello, was surfing on stackoverflow forums when I came across this:
The
onerror attribute, I tried it, seems really nice, when my img src is invalid, I got that custom image instead of that little icon which appears when image is not loaded.
I wanted to discuss a bit about what the onerror is and when it occurs, from what I've read, it occurs each time an internal resource (video/img) fails to load?
How does the this.onerror=null; work though? I read that we need it to prevent an infinite loop.12 Replies
onerror is an event that happens when the image can't be displayed for any reason
the this.onerror=null is to prevent an infinite loopyep, which runs first,
this.onerror=null or the this.src?left to right
yeah I see
so the flow is like that :
img tries to load original src, if img fails to load, onerror is triggered, immediate, the event is set to null to prevent an infinite loop of the onerror event. After onerror has been set to null, load fallback image?
if the onerror on this img tag wouldn't have been set to null and the fallback image wasn't loaded properly, this would be on going infinitely?
yes
and yes
because the
onerror would keep triggeringyep, really interesting didn't know about that, is the onerror something we use frequently or it has its limitations?
we just don't use it
you can, there's absolutely nothing wrong with that
but we just don't use it
yupp, noted, thanks !
the only limitation is that you have no idea why the image failed
suddenly offline? invalid image? unsupported format? partial download of an image that isn't progressive? 404 error?
you won't know from the
onerror itselfyeah true, will be vigilant when using it
there's nothing to be vigilante about it
you just don't know why there's an error
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/error_event
yep