James Cazzetta
James Cazzetta

Reputation: 3220

Check if image exists without loading it

I am currently using following script in a hover-functionality:

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

It loads every image each after the other, causing to slow down the entire website (or even crashing).

Is there a way to check if an image exists, though prevent loading it (fully) using javascript?

Thanks alot!

Upvotes: 4

Views: 13878

Answers (4)

wiktor
wiktor

Reputation: 1637

My solution:

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."));

Upvotes: 1

Asif hhh
Asif hhh

Reputation: 1552

Here's how you can check if an 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 http://jsfiddle.net/jeeah/

Upvotes: 0

Mevin Babu
Mevin Babu

Reputation: 2475

There's no way determining using javascript or jQuery if an image exists without loading it.

workaround:

The only way to check if an image exists on the server side would be to try loading the image to a hidden div or something and check if the image is there or not and then display it.

or you can use some server side language of your choice like ( php, asp, jsp, python, etc ) and send the request to the image to the server side language (preferably using AJAX) and let the server side script check if the image exists or not and send back the image if present or sent an error code if not present.

Upvotes: 1

Jay Blanchard
Jay Blanchard

Reputation: 34416

Since JavaScript (and therefore jQuery) is client-side and the image resides server-side before loading there is no way to check to see if the image exists without using Ajax or your server-side scripting to make sure the image exists.

Upvotes: 3

Related Questions