Detect 404 response code when loading an img tag?

by David Iglesias

HTML

<p>The red dot below is an image that returned 404 status code, but a transparent 1x1 gif:</p>
<div id="imageDiv"></div>
<p id="stats"></p>
<p>(Look at the JS console)</p>

CSS

* {font-family: sans-serif;}
body {
  background-color: black;
  color: white;
}

img {
  background-color: red;
}

JavaScript

// Image URL
let imgSrc = "https://encrypted-tbn1.gstatic.com/licensed-image?q=tbn:ANd9GcS4P7jubiSlwl1SB7yvdkIAbxQ-2R88kaF1L4yYtBqLhzhe1r5RmkyplN-xxrQkN2EEcWeyqH-TNw7v6ic";

// Attempt to see if `imgSrc` returns a 404 status, without CORS.
async function checkImage(imgSrc) {
  // fetch won't let me look at the status code
  const response = fetch(imgSrc);
  response.then((response) => {
    console.log("Fetch status:", response.status);
  }, (reason) => {
    console.log("Fetch rejected:", reason);
  })
  // XHR won't either
  const xhr = new XMLHttpRequest();
  xhr.open('GET', imgSrc, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) { // Request is complete
      console.log("XHR status:", xhr.status);
    }
  };
  xhr.send();
}

function injectImage(imgSrc) {
  let imgTag = document.createElement('img');
  imgTag.addEventListener('error', (e) => {
    console.log('img error:', e);
  });
  imgTag.addEventListener('load', (e) => {
    let img = e.target;
    console.log('img load:', e);
    // We can see if the image is 1x1 here:
    console.log(e.target.width);
    stats.innerText = `Image loaded. Size: ${img.width} x ${img.height} px.`;
  });

  imageDiv.append(imgTag);
  imgTag.src = imgSrc;
}

injectImage(imgSrc);
checkImage(imgSrc);