Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fallback image and timeout - External Content. Javascript

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.

like image 570
Boris Smirnov Avatar asked Oct 19 '09 14:10

Boris Smirnov


People also ask

What is fallback in Javascript?

js applications. A fallback function specifies an action that is performed whenever a call to a remote service fails. For example, you can use a fallback function to send a customized message about service failures to the client.

What is fallback images?

By adding a fallback image, you can set a branded image to be used when no post thumbnail is found. This allows you to make sure that all your articles have a post thumbnail.

How do I add a fallback image?

We can use the onerror attribute on the image to set a fallback. We use the onerror to set the error to null and set the src of the image to a fallback.


2 Answers

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.

like image 50
Craig Stuntz Avatar answered Oct 24 '22 03:10

Craig Stuntz


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.

like image 21
moxn Avatar answered Oct 24 '22 03:10

moxn