简体   繁体   中英

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...

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

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.

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";
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM