Image background fallback using <img/> tag error handlers

In the project I’m working on, we make large use of external assets like images, coming from several providers. Unfortunately these links are often broken, resulting in “empty squares” which are unpleasant for the user. The best thing to do, since we don’t have the full control over these resources, is to display the classic “image not available” pic, but this is not simple as writing an if statement such:

if (record.image) {
    <img src="record.image" />
} else {
    <img src="imageNotAvailableLink" />

because in our case “record.image” is defined although its path is unreachable. So, we have to try to load the image and replace it at runtime when we know that the src is broken. How can we catch that exception? We just need to listen to onerror and onabort img events, so we can simply write this smart img tag:


The this key inside an event attribute, refers to the dom node itself, so we can switch an attribute like src with a little piece of inline JavaScript.
Anyway in my scenario the problem is bigger than this example, because thumbs images are rendered as divs background in order to make a sort of polaroid effect and, at the same time, to solve a potential issue related to exceeding image dimensions or a stretched one.
Fortunately the solution I found, is not so far from the above, the only difference is that I used an invisible img tag located inside the div and when it catch the error rather than change its src it changes its parent background:

Of course in my final implementation I replaced the piece of inline js assignment with an utility function call that does the job and also trace a debug message to the console, displaying the path of the broken image… I’m pretty satisfied about my work :^)