Madan Sapkota
Madan Sapkota

Reputation: 26091

checking image existance from client side

I am developing one image gallery website, which may have thousands of photos in future. All the images comes from other Website / API or user uploads.

User uploaded images

<img src="../images/example.jpg" alt="" />

External Images

<img src="http://example.com/xyz.jpg" alt="" />

Let say, image deleted from external website. Is there a way to check photo exists from client side using jQuery / JavaScript etc?

What I think is

i) I hotlink the image from external website

ii) Image deleted from external website, when website first load, jquery will send me the dead link info to server using ajax etc

iii) I will fix the link.

Thanks in advance...

Upvotes: 1

Views: 242

Answers (3)

Kerem
Kerem

Reputation: 11576

You can use onerror event in this case.

var imgs = document.getElementsByTagName("img"),
    img, i = 0;
while (img = imgs[i++]) {
    img.onerror = function() {
        // just an example for error reporting
        Ajax.send("POST /image_error.php", {src:img.src});
        // change img src
        img.src = "images/error.jpg";
    };
}

Upvotes: 0

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

You could do something like this...

$(function() {
    $(document).on("error", "img", function() {
        // do something with $(this) here
    });
});

That would detect broken images and allow you to do something about it.

Upvotes: 0

Louis Ricci
Louis Ricci

Reputation: 21086

You could use the "onerror" event on your external images and create a server side script to handle the error and return a generic "image not found" image while you fix the issue.

Something like ...

onerror="this.src='/fiximage.php?q='+this.src;"

Upvotes: 1

Related Questions