Some days ago I was doing something to personalize my Github profile page and I needed a way to display an image in case the loading of one from a service was failing (if you are curious you can read it here).
So I needed a basic fallback for an image, should not be an issue, right?
<img src="https://not-existing-url/not-existing-image.jpeg" onerror="this.src = 'error.jpg';"
The problem for me is that I needed an HTML pure solution because Github strips every script from the readme (for security reasons).
Fun fact: I've found a solution but that doesn't work anyway in Github profile page because this solutions uses a tag that is removed too, always for security reasons
So after some search and digging I've found this solution (thanks to Patrick McElhaney)
<object data="https://not-existing-url/not-existing-image.jpeg" type="image/jpg"> <img src="fallback-image.jpeg" /> </object>
That's it. You can see it (and play with it) in the codepen below
The solutions involves the
object tag as you may have noticed. This is a pretty unknown HTML element that can be used to display multimedia content, like videos, images, PDFs and so on.. It can be used also to display other webpages, so it may be though as the brother of
iframe. It will display what you pass in the
data attribute, instead the HTML you put 'inside' the tag is going to be used as a fallback in case the browser does not support the tag or if the source is not correctly loaded. So this works great for both old browsers and for content that fails to load (like in my case).
As always if you want to dig deeper MDN docs are always the first place to go.
So this is the only solution I've found really working with just HTML.
There are solutions also with CSS but they involves knowing the image dimensions, and that was not ok in my case because the embedded image was dynamic.
If you know a better approach please comment here or reach me on my twitter