The other day I discovered that the img tag has an error event. This can be used to automatically load a fall back image when the main image fails for some reason. We encounter this in our dev sites sometimes, because the data is often not 100% correct. For example, our application may ‘think’ there is an image for a product (according to the database), so it writes out an img tag for it. But the image file does not actually exist. So we may end up with a broken image icon, or depending on the browser there may be no indication at all that something is wrong. The tester may get confused as to what’s gone wrong. So I added this code to show an ‘image file does not exist’ image:
<img src="#productImage#" onerror="this.src='/images/icons/imageDoesNotExist.png'" >
That’s it. Be careful that in your error handling code you point to an image file that really exists, otherwise you could go into an infinite loop. One way to be safe regarding that would be to call a function, and remove the onerror attribute so that it only gets fired once.
<script>
function imageError(element) {
element.onerror='';
element.src='/images/icons/imageDoesNotExist.png';
}
</script>
<img src="#productImage#" onerror="imageError(this)">
You could even use this to report a broken image:
<img src="#productImage#" onerror="this.src='logBrokenImage.cfm?image=' + this.src" >
The onerror event is supported in all major browsers. The other tags that support onerror are object, script, and style.