1. Technology
Send to a Friend via Email

Your suggestion is on its way!

An email with a link to:

http://javascript.about.com/library/blfailimg.htm

was emailed to:

Thanks for sharing About.com with others!

Failsafe Remote Images

Join the Discussion

Questions? Comments?

Often the code given to you for displaying ad banners etc. remote loads an image from the advertisers site. This is one of the few instances where you may want to actually load a remote image since that allows the advertiser to change their advertising image as appropriate without your having to take any action.

There is a problem though when their site is down for any reason because your site then has an image missing from the page and doesn't display as nicely as you would like. How can we tell when a remote image has failed to load and what can we do when it does?

Internet Explorer supports the onerror event handler on images which can be triggered when the image fails to load. Unfortunately that is the only browser that supports that event on images. The image.complete property is set true when the image finishes loading. Most browsers leave this as false if the image fails to load but unfortunately the mozilla based browsers such as Netscape and Firefox still set this true when the image is load fails. I have seen several sites offering a solution to this based on one or other of these but neither offers a complete solution that works on all browsers.

The following code added to the head of your page solves this by taking a copy of each image after loading and then testing how wide the copy of the image is. If the width is zero then the image didn't load and an alternate image from your site (graphics/myimg.gif in this example) can be substituted.

function failsafeImg(){
var badImg = new Image();
badImg.src = 'graphics\/myimg.gif';
for(var i=0;i<document.images.length;i++){
var cpyImg = new Image();
cpyImg.src = document.images[i].src;
if(!cpyImg.width){
document.images[i].src = badImg.src;
}
}
}
onload = failsafeImg;

Note that a copy of each image is taken because the original in your page should have a width attribute specified both in order to comply with the HTML standards and also so that if you use a transparent 1x1 gif image as your replacement image that it knows how big it should display on the screen. This width will be what comes up if we test the original image in the page. If we only copy the image.src then the width of the copy will be the actual width of the image itself and not that defined in the page.

You could alter this code to display different images depending on which image fails to load by testing for the appropriate values for i in the loop.

©2014 About.com. All rights reserved.