Explain Codes LogoExplain Codes Logo

How to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

html
responsive-design
performance
best-practices
Alex KataevbyAlex Kataev·Oct 23, 2024
TLDR

Ensure an image fallback with onerror in HTML by replacing a missing image's src with an alternative URL:

<img src="original.jpg" onerror="this.src='fallback.jpg'; this.onerror=null;" alt="">

Key points:

  • onerror fires when the image fails to load.
  • "this.src='fallback.jpg'; this.onerror=null;" swaps to a backup image and nullifies the onerror 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:

<img src="original.jpg" onerror="if(this.src !== 'fallback.jpg') this.src='fallback.jpg';" alt="">

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:
$('img').error(function() { if (this.src !== 'fallback.jpg') { this.src = 'fallback.jpg'; // Because second chances are beautiful! } });
  • Doubly verify image existence by checking its width after a failed load:
window.onload = function() { var img = document.getElementById('myImage'); if (!img.naturalWidth) { // "It's not you, it's me." - Browser, probably. img.src = 'fallback.jpg'; } }

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:
<?php $src = file_exists('original.jpg') ? 'original.jpg' : 'fallback.jpg'; ?> <img src="<?php echo $src; ?>" alt=""> // PHP, at your service!

One fallback to rule them all

If you're dealing with multiple images, here's a global error handler:

function imageError(image) { image.onerror = null; image.src = 'fallback.jpg'; // "In error-handling, we trust." - All images, probably } // Usage <img src="original.jpg" onerror="imageError(this)" alt="">

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:

var img = new Image(); img.onload = function() { // "I'm alive!" - Image, most likely. }; img.onerror = function() { this.src = 'fallback.jpg'; // "Oopsie daisy..." - Image, definitely. }; img.src = "original.jpg";

Harness the power of onload

Buckle up onload! It can confirm the image has loaded successfully:

<img src="original.jpg" onload="console.log('Hooray! Successful load!')" onerror="this.src='fallback.jpg';" alt="">

CSS-powered visual consistency

A CSS background can provide a visually pleasing fallback, maintaining layout integrity:

.img-holder { display: inline-block; width: 200px; height: 200px; background-image: url('fallback.jpg'); background-size: cover; // One size fits all, right? } .img-holder img { width: 100%; height: auto; }
<div class="img-holder"> <img src="original.jpg" onerror="this.style.display='none'" alt=""> // If it fails, make it disappear! 🎩🐇 </div>