5

Through (native) javascript, i want to check if an image exists. I have found this script:

function imageExists(image_url){
    var http = new XMLHttpRequest();
    http.open('HEAD', image_url, false);
    http.send();
    return http.status != 404;
}

from this question. However, everytime i run this, it throws me a HEAD error message whenever it does not find an image (in the console). Can i get rid of this error whenever it fails to find something?

The onload/onerror solution in the comments at the linked question also give me the same issue, with reporting errors.

Community
  • 1
  • 1
Davy
  • 691
  • 1
  • 7
  • 18
  • I do not think there is any way around it. – epascarello Oct 23 '15 at 13:20
  • It's generally browser-level behavior to print out HTTP responses above the 3xx range. It wouldn't be helpful for debugging if it weren't consistent. If you could instruct the server to return something like a 204 (The server successfully parsed the request, but is not returning any content) for a particular URL range, that might stop the error. – Katana314 Oct 23 '15 at 13:25
  • This is new information for me, and although it's helpful, i do not have control over the server settings, so unfortunately this is not an option for me. – Davy Oct 23 '15 at 13:35

1 Answers1

-1

Try this

function imageExists(url, callback) {
   var img = new Image();
   img.onload = function() { callback(true); };
   img.onerror = function() { callback(false); };
   img.src = url;
}

// Sample usage
var imageUrl = 'image_url';
imageExists(imageUrl, function(exists) {
alert(exists);
});

check out Checking if image does exists using javascript

Community
  • 1
  • 1
Vinodhan
  • 110
  • 4