Change image source if file exists

Here is a modern Promise based way, which will return a Promise with a boolean value.

function imageExists(src) {
    return new Promise((resolve, reject) => {
      var img = new Image();
      img.onload = function () {
        resolve(true);
      }
      img.onerror = function (error) {
        resolve(false);
      }
      img.src = src;
    })
}


const imagePath = "http://www.google.com/images/logo_sm.gif";
imageExists(imagePath).then(doesExist => {
  console.log('doesImageExist', doesExist);
});
  

You can of course use async/await syntax for this.

const doesImageExist = await imageExists(imagePath);

The Same Origin Policy prevents you from making AJAX requests to other domains. Unless you're running this on "http://www.mojopin.co.uk", this code won't work.


You don't have to use AJAX to do this, since you can hot-link images from other domains without any restrictions. Here's how you can check if an image exists:

function checkImage(src) {
  var img = new Image();
  img.onload = function() {
    // code to set the src on success
  };
  img.onerror = function() {
    // doesn't exist or error loading
  };

  img.src = src; // fires off loading of image
}

Here's a working implementation http://jsfiddle.net/jeeah/