0

As topic simply puts it. Is there any method to display/use another image source file if image file doesn't exist?

I'm simply drawing elements with javascript and assigning sources to them.

1 Answers1

2

Without AJAX you can do something like this

 function checkIfExists(src) {
      var img = new Image();
      img.onload = function() { 
            //
      };
      img.onerror = function() {
        // load another src
      };

      img.src = src; 
    }

Fiddle

You can also check the http status.

function checkIfExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
} 
Ken de Guzman
  • 2,790
  • 1
  • 19
  • 33