Fallback image and timeout - External Content. Javascript
Asked Answered
P

2

38

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.

Proclamation answered 19/10, 2009 at 14:4 Comment(1)
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.Astrix
F
62

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.

Fuchs answered 19/10, 2009 at 14:13 Comment(4)
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...Seiler
Awesome! Love it when I learn new tricks like this. I was going to resort to some jQuery jiggery pokery.Wattage
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.Keane
Thank you so much. it's very fantasticCawley
S
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.

Seiler answered 19/10, 2009 at 14:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.