views:

152

answers:

3

After a user uploads a file we have to do some additional processing with the images such as resizing and upload to S3. This can take up to 10 extra seconds. Obviously we do this in a background. However, we want to show the user the result page immediately and simply show spinners in place until the images arrive in their permanent home on s3.

I'm looking for a way to detect that a certain image failed to load correctly (404) in a cross browser way. If that happens, we want to use JS to show a spinner in it's place and reload the image every few seconds until it can be successfully loaded from s3.

+4  A: 

Handle the <img> element's onerror event.

SLaks
@xal: Just be sure to hook the `error` event *before* you set the `src` property (if you're doing this with `new Image` or `document.createElement("img")` rather than via an HTML string). Otherwise, you're in a race condition and the event could fire before you start handling it (just like the `load` event).
T.J. Crowder
@T.J: Not necessarily. Javascript runs on the UI thread, so if you handle the event immediately after setting `src`, there shouldn't be any risk. However, you're still right,
SLaks
@SLaks: Javascript runs on the Javascript thread, which on *some browsers* is also the UI thread. It is not necessarily the download thread. I've helped people fix bugs caused by precisely this, setting `src` before setting a `load` handler. There's a race condition there. If you already have the handler registered, the event handling code will put it on the execution stack to be run once the JS thread is available to do something else. If you don't, you can miss the event.
T.J. Crowder
A: 

This site details how to do it.

Detecting Broken Images in JavaScript

griegs
+1  A: 

http://lucassmith.name/2008/11/is-my-image-loaded.html

This might help.

unomi
This raises a good point. You (OP) need to load the images with random querystring parameters.
SLaks