Created
January 19, 2023 23:16
-
-
Save ridhotegar/6cb69595bf0b86e2301b98b5510419cb to your computer and use it in GitHub Desktop.
Handle broken image or link with JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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