Search code examples
javascriptjqueryfile-exists

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


Solution

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