Graceful handling of the display of remote images that might no longer be there
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?
精彩评论