Get HTTP status code or response headers from an <img> tag?

In this service that I create, an image request can lead to two possible answers.

  • He responds with the requested image.

  • It responds with a default image and indicates that the requested image is not immediately available. In this case, the request may be repeated.

The obvious ways to indicate case # 2 are either to respond with a status code of 202 or an X-Retry-In header. However, I am open to suggestions.

In any case, my goal is to somehow catch this answer in JS (http-header / status code / other ideas are welcome) and automatically repeat the image after a few seconds.

I know that something approximating this can be done using ajax, but I would prefer a solution that uses only JS + <img> tags.

+5
source share
1 answer

Try something like this:

 $.ajax({ type: "GET", url: "YOURURL", dataType: "image/png", success: function(img) { i = new Image(); i.src = img; // your image }, error: function(err) { i = new Image(); i.src = 'http://website.site/image.png' // your error image } }); 
0
source

All Articles