js test if image error code example
Example 1: javascript how to check if image exists
// create an XHR object
const xhr = new XMLHttpRequest();
// listen for `onload` event
xhr.onload = () => {
if (xhr.status == 200) {
console.log('Image exists.');
} else {
console.log('Image does not exist.');
}
};
// create a `HEAD` request
xhr.open('HEAD', '/img/bulb.svg');
// send request
xhr.send();
Example 2: js detect all images errors
window.addEventListener("error", e => {
/* query selector images */
// image element on error => replace source
})