Fallback mechanism when img src is invalid

Hello, was surfing on stackoverflow forums when I came across this:
onerror="this.onerror=null;this.src='images/404-error.png';"
onerror="this.onerror=null;this.src='images/404-error.png';"
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
ἔρως
ἔρως2mo ago
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 loop
Faker
FakerOP2mo ago
yep, which runs first, this.onerror=null or the this.src?
ἔρως
ἔρως2mo ago
left to right
Faker
FakerOP2mo ago
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?
ἔρως
ἔρως2mo ago
yes and yes because the onerror would keep triggering
Faker
FakerOP2mo ago
yep, really interesting didn't know about that, is the onerror something we use frequently or it has its limitations?
ἔρως
ἔρως2mo ago
we just don't use it you can, there's absolutely nothing wrong with that but we just don't use it
Faker
FakerOP2mo ago
yupp, noted, thanks !
ἔρως
ἔρως2mo ago
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 itself
Faker
FakerOP2mo ago
yeah true, will be vigilant when using it
ἔρως
ἔρως2mo ago
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
Faker
FakerOP2mo ago
yep

Did you find this page helpful?