开发者

Graceful handling of the display of remote images that might no longer be there

开发者 https://www.devze.com 2023-01-14 10:55 出处:网络
i am displaying remote images on my service <img src=\"http://remote-site.com/imageX\"> However, sometimes the image is already gone, so I would get 404s or just a plain text.

i am displaying remote images on my service

<img src="http://remote-site.com/imageX">

However, sometimes the image is already gone, so I would get 404s or just a plain text.

Question is -> how can i degrade to a generic image as soon as I get something that is not image type?

Ac开发者_Go百科tual code, whether in jQuery, Ruby, etc much appreciated!


The error event is fired when the image can't be loaded for any reason (connection error, HTTP 404, not image data, et cetera). A really simple inline example would be

<img src="http://example.com/image.jpg" onerror="this.src = 'generic-image.png';" />

Of course if you want to do this properly, do it in jQuery or another library:

$("img.external").bind("error", function() { // assuming your external images have this CSS class
    this.src = "generic-image.png";
});


If you write PHP you could use:

<?= (file_exists('http://remote-site.com/imageX'))?'<img src="http://remote-site.com/imageX">':'<img src="http://remote-site.com/genericImage.png">' ?>

This would check to see if the image is there, and display a generic image that you create and host somewhere if it does not.

I use this for User images in applications. If they have not uploaded an image, the generic is displayed.

Are these images coming from a Database?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号