fallback img src that failed to load
12/6/2022, 12:19:06 PM
by Leo Voon
When your img failed to load, your browser will fallback to show the alt. To have better UX on this, we could set a default styling to it. We should on:error. Read more in MDN.
In plain HTML + JS:
<!-- html file -->
<img id="image" src="https://broken-link-goes-here" />
// js file
const img = document.getElementById("image")
img.addEventListener("error", function(event) {
event.target.src = "https://default-image-link-goes-here"
event.onerror = null
})