Detecting an image 404 in Javascript

Tobias Lütke picture Tobias Lütke · Jun 11, 2010 · Viewed 53.8k times · Source

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.

Answer

SLaks picture SLaks · Jun 11, 2010

Handle the <img> element's onerror event.