I have anchor tags like so:
<a href=\"http://www.duckbill.com" target=\"_blank\"><img height=\"160\" width=\"160\" src=\"http://images.duckbill.com/PlatypiOnVacation.jpg\" alt=\"Platypi playing Pinochle and eating Pizza in Panama\" /></a>
...that sometimes fail to load the src image; in such cases I'd like to, after a sufficient delay (a couple of seconds), replace that with:
<a href=\"http://www.duckbill.com" target=\"_blank\"><img height=\"160\" width=\"160\" src=\"Content/Images/PlatypiOnVacation.jpg\" alt=\"Platypi playing Pinochle and eating Pizza in Panama\" /></a>
I know that I could probably do that in jQuery, but how would I be able to programmatically determine that the remote file did not load and, when such is the case, respond by using the fallback image?
I like Brad Christie's answer for truly unavailable images, but I want to never show an "unavailable" - just use a local one if a remote one is not available at the moment. I like this: http://www.cirkuit.net/projects/jquery/onImagesLoad/example1.html but how to determine programmatically that the image failed?
<img src="http://remotecdn.com/myimage.jpg"
data-failover="/assets/notfound.jpg" />
Then:
<script>
$('img[data-failover]').error(function(){
var failover = $(this).data('failover');
if (this.src != failover){
this.src = failover;
}
});
</script>
Attempt to load the actual source, but in the event of an error use the failover
data property to convert it to a local resource. Since we're keeping the supplemental information separated, it should gracefully fail in browsers that can't/won't support it.
More information about .error()
.
The problem I have found is that image requests sometimes hang for quite a while. If you want to show something to the user when that happens you can set a CSS background on the img element with a 'not available' icon etc. Then if the image does eventually load it will still display.
setTimeout(function(){
$(".thumb").each(function(){
if(!this.complete){
$(this).css({background:'url("not-available.gif")'});
}
});
}, 5000);
I have found a CSS solution: overlap images.
In my case I had 2 profile images, one image is of the user, if it exists, if it does not exist, then an avatar will be used. We don't know if the user image exists.
So if the intended image does not exist, the avatar shows up :)
//CSS
.avatar {
position:relative;
height: 40px;
width: 40px;
}
.avatar img {
position: absolute;
top: 0px;
}
//HTML
<div class="avatar">
<img height="40" width="40" src="/assets/users/avatar.jpg">
<img height="40" width="40" src="/assets/users/joe.jpg" >
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With