Defaulting Images When Originals Don’t Exist

I needed to a profile image of some people recently. However, the profile images are hosted on another server and some people don’t have pictures. Unfortunately there’s no sure fire way to test for the existence of an image on a remoter server other than a cURL script to load a header and check for a 404 error. Since I’m loading over 600 images on one page, I needed a simpler solution…

The answer is to load your first image in an object tag, if that image doesn’t exist, you can include a default child image to take it’s place. Check it:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
<title>Object Test</title>
</head>
<body>   

  <object data="http://stackoverflow.com/does-not-exist.png">
    <img src="https://stackoverflow.com/content/img/so/logo.png">
  </object>

</body>
</html>

An HTML only solution is kinda nice once in a while. Bam!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.