How to show alternate image if source image is not found? (onerror working in IE but not in mozilla)
Ensure an image fallback with onerror
in HTML by replacing a missing image's src
with an alternative URL:
Key points:
onerror
fires when the image fails to load."this.src='fallback.jpg'; this.onerror=null;"
swaps to a backup image and nullifies theonerror
to prevent an infinite loop.- This is a compact solution for handling image errors.
The full journey of onerror
I'm going to share several interesting situations and solutions to illustrate how you can get the most from the onerror
event.
Dodge the infinite loops
Infinite loops? Not on my watch! The script can run forever if the backup image also fails to load. Here's a way to sidestep that:
Universal browser harmony
Fun fact, onerror
doesn't play nice with some Firefox versions. Let's ensure all browsers are on board.
- Use jQuery's
error()
method across all browsers:
- Doubly verify image existence by checking its width after a failed load:
Buddy system: The server got your back!
In addition to client-side handling, consider a server-side ally:
- Use PHP's
file_exists()
to ensure the image exists before rendering the tag:
One fallback to rule them all
If you're dealing with multiple images, here's a global error handler:
Extra level: Advanced error handling
Why stop at good enough when you can make your image error handling even more robust?
Direct src assignments with JavaScript
Dynamically create image elements with JavaScript for enhanced control:
Harness the power of onload
Buckle up onload
! It can confirm the image has loaded successfully:
CSS-powered visual consistency
A CSS background can provide a visually pleasing fallback, maintaining layout integrity:
Was this article helpful?