Check if image exists without error message

Cross-cutting (native) javascript, I want to check if the image exists. I 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, every time I run this, it gives me a HEAD error message whenever it does not find the image (in the console). Can I get rid of this error whenever it does not find something?

The onload / onerror solution in the comments on a related question also gives me the same problem with error messages.

+5
source share
1 answer

try it

 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 Check for image using javascript

0
source

Source: https://habr.com/ru/post/1234368/


All Articles