Skip to content

Instantly share code, notes, and snippets.

@ridhotegar
Created January 19, 2023 23:16
Show Gist options
  • Save ridhotegar/6cb69595bf0b86e2301b98b5510419cb to your computer and use it in GitHub Desktop.
Save ridhotegar/6cb69595bf0b86e2301b98b5510419cb to your computer and use it in GitHub Desktop.
Handle broken image or link with JavaScript
<script>
document.addEventListener("DOMContentLoaded", function() {
let images = document.querySelectorAll("img");
images.forEach(img => {
img.addEventListener("error", function () {
console.log("Broken image: ", img);
img.src = `https://fakeimg.pl/${img.width}x${img.height}/`;
});
let xhr = new XMLHttpRequest();
xhr.open('GET', img.src, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status === 200) {
var imgBlob = this.response;
}
}
xhr.onerror = function() {
img.src = `https://fakeimg.pl/${img.width}x${img.height}/`;
};
xhr.send();
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment