35

What is the best way to set up a local fallback image if the external image does not load or takes too long to load.

Boris Smirnov
  • 1,217
  • 4
  • 15
  • 27
  • Brilliant! I was just about to ask the same question, and I did a quick google search and found this question. I was thinking of doing it server side, but client side sounds much more straightforward. – Skilldrick Jan 14 '10 at 12:18

2 Answers2

59

You can add an onerror handler:

<img
  src="http://example.com/somejpg.jpg"
  onerror='this.onerror = null; this.src="./oops.gif"'
/>

Note: Setting onerror to null in the handler, so that the webpage doesn't crash if oops.gif can't be loaded for some reason.

Anvesh Checka
  • 3,787
  • 2
  • 21
  • 28
Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • Oh, I forgot about onerror. This might be easier, but the solution I posted below allows to precache the images and check their availability before they have to be displayed. Depends on what you need... – moxn Oct 19 '09 at 14:23
  • Awesome! Love it when I learn new tricks like this. I was going to resort to some jQuery jiggery pokery. – MikeMurko Feb 25 '12 at 18:51
  • The problem here is the time by which the image regarded as not available ! It may take long time the browser activity loading works till it invoke the `onerror` event. – SaidbakR Dec 31 '15 at 17:25
  • Thank you so much. it's very fantastic – Albaz Nov 05 '19 at 10:06
2

Try to make use of the Image.complete property.

var img = new Image(w,h)
img.src = "http://...";

Now check periodically if img.complete is true and call some fallback mechanism shuold it still be false after n seconds.

moxn
  • 1,790
  • 1
  • 15
  • 34