0

Is there anyway in javascript to test if a src of an image is actually hitting a real file?

My thought is that at some point in the DOM construction the browser has to realize that the file location is not returning a real file because it defaults to the broken file.

Todd Vance
  • 4,627
  • 7
  • 46
  • 66

2 Answers2

2

Yes, you can leverage the onerror event for the image element.

Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132
1

Function I use in my library for this incident:

function onImageError (source) {
    //NOTE: Image Error function 
    //Useage: <img src="" onerror="onImgError(this)" />

    source.src = "/public/images/global/backup_product.jpg"; // location of sample/error image
    source.onerror = ""; // disable onerror to prevent endless loop
    return true;
}
Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96