Check if the image exists without loading it.

I am currently using the following script in the hover function:

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

It loads each image one after another, which slows down the entire website (or even crashes).

Is there a way to check if an image exists , but prevent it from loading (completely) using javascript?

Thanks a lot!

+3
source share
4 answers

Since JavaScript (and therefore jQuery) is the client side and the image remains on the server side before loading, there is no way to check if the image exists without using Ajax or server-side scripts to make sure the image exists.

+3
source

There is no way to determine if javascript or jQuery is used if the image exists without loading .

workaround

The only way to check if the image exists on the server side is to try loading the image into a hidden div or something else and check if this image is there or not, and then display it.

or you can use any server language of your choice, for example (php, asp, jsp, python, etc.), and send an image request to the server language (preferably using AJAX), and check the server side of the script, whether the image exists or not, and send the image if it is, or send an error code if it is missing.

+1
source

Here you can check if the 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 of http://jsfiddle.net/jeeah/

0
source

My decision:

 function imageExists(url) { return new Promise((resolve, reject) => { const img = new Image(url); img.onerror = reject; img.onload = resolve; const timer = setInterval(() => { if (img.naturalWidth && img.naturalHeight) { img.src = ''; /* stop loading */ clearInterval(timer); resolve(); } }, 10); img.src = url; }); } 

Example:

 imageExists(url) .then(() => console.log("Image exists.")) .catch(() => console.log("Image not exists.")); 
0
source

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


All Articles