How to get HTTP status code of <img> tags

http status codes
http status code 404
http status code 400
http status codes cheat sheet
http status code 200
error code list
http 201 vs 200
custom http status codes

I have a page with a lot of images that are generated server-side depending on user actions. And when image loads successfully I'm happy, but when there is an error on the server I have to act according to what an error occurred.

For example:

  • 500 code: do this stuff.
  • 503 code: do that stuff

and so on.

So, my question: is there any way to get status code within "img" tag on-error event handler?

No, there is no way to get the HTTP status from a request made by an img tag in JavaScript.

You could write a firefox plugin, chrome/safari extension to do that.

An alternative would be using AJAX to load your images (not using img tags). You can get Http Status Codes from Ajax Requests.

How to Check HTTP Status Code: Server Response Codes in , 2xx: Success It means the action was successfully received, understood, and accepted. As per 'dtb' you need to use HttpStatusCode, but following 'zeldi' you need to be extra careful with code responses >= 400. This has worked for me: HttpWebResponse response = null; HttpStatusCode statusCode; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException we) { response = (HttpWebResponse)we.Response; } statusCode = response.StatusCode; Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); sResponse = reader.

You cannot check HTTP status this way. However you can check if image was loaded or not using naturalWidth property.

if (img.naturalWidth === 0) {
    // do sth

Hope it help.

List of HTTP status codes, 3xx: Redirection It means further action must be taken in order to complete the request. Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse) If myHttpWebResponse.StatusCode = HttpStatusCode.OK Then Console.WriteLine(ControlChars.Lf + ControlChars.NewLine + "Response Status Code is OK and StatusDescription is: {0}", myHttpWebResponse.StatusDescription) End If ' Release the resources of the response.

You may combine the couple technics to get img.status:

<img src="/no.img" onerror="error(this)">

function error(img) {
   var r = makeXMLHttpRequestAgain(img.src);
   if (r.status === 500) img.src = '/e500.img';
   if (r.status === 503) img.src = '/e503.img';

HTTP - Status Codes, help identify the cause of the problem when a web page or other resource does not load properly. This is a list of Hypertext Transfer Protocol (HTTP) response status codes. Status codes are issued by a server in response to a client's request made to the server. It includes codes from IETF Request for Comments (RFCs), other specifications, and some additional codes used in some common applications of the HTTP.

 function loadBinaryImageAndInsertToImgTag(imgElement, imageUrl) {
        let xhr = getXMLHttpRequest();
        xhr.onreadystatechange = ProcessResponse;"GET", imageUrl, true);
        xhr.overrideMimeType('text/plain; charset=x-user-defined');

        function getXMLHttpRequest() {
            let xhr = null;

            if (window.XMLHttpRequest || window.ActiveXObject) {
                if (window.ActiveXObject) {
                    try {
                        xhr = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (e) {
                        xhr = new ActiveXObject("Microsoft.XMLHTTP");
                } else {
                    xhr = new XMLHttpRequest();
            } else {
                alert("Your browser does not support XMLHTTP");
                return null;
            return xhr;

        function ProcessResponse() {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    imgElement.src = "data:image/jpeg;base64," + encode64(xhr.responseText);
           = "";
                } else {
                    alert("Error retrieving data!");

        function encode64(inputStr) {
            let b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
            let outputStr = "";
            let i = 0;

            while (i < inputStr.length) {
                let byte1 = inputStr.charCodeAt(i++) & 0xff;
                let byte2 = inputStr.charCodeAt(i++) & 0xff;
                let byte3 = inputStr.charCodeAt(i++) & 0xff;
                let enc1 = byte1 >> 2;
                let enc2 = ((byte1 & 3) << 4) | (byte2 >> 4);
                let enc3, enc4;
                if (isNaN(byte2)) {
                    enc3 = enc4 = 64;
                else {
                    enc3 = ((byte2 & 15) << 2) | (byte3 >> 6);
                    if (isNaN(byte3)) {
                        enc4 = 64;
                    else {
                        enc4 = byte3 & 63;
                outputStr += b64.charAt(enc1) + b64.charAt(enc2) + b64.charAt(enc3) + b64.charAt(enc4);
            return outputStr;

What Are HTTP Status Codes?, In the main window of the program, enter your website homepage URL and click on the 'Start' button. As soon as crawling is complete, you will have all status codes in the corresponding table column. Pages with the 4xx and 5xx HTTP status codes will be gathered into special issue reports. I suspect that without using HttpWebRequest and HttpWebResponse, a distinct status code may not be available. It occurs to me that, if you are not interested in intermediate status codes, you can safely assume the final status code is in the 2xx (successful) range, otherwise, the call would not be successful.

You have to add an eventListener on images :

For example with jQuery :

    .error(function(e) {
        //add your unhappy code here

        //unbind if needed
    .load(function(e) {
        //add your happy code here

        //unbind if needed

Status codes in HTTP, The values of the numeric status code to HTTP requests are as follows. When received in the response to a GET command, this indicates that the returned  Hey there, any ideas on how to perform a retry (if statusCode != 200), from within the response callback? – user1893702 Oct 26 '15 at 22:23

A Complete Guide and List of HTTP Status Codes (2020), HTTP status codes are like short notes from a server that get tacked onto a web page. They're not actually part of the site's content. Instead  An HTTP status code is a message the server sends when a request made by a browser can or cannot be fulfilled. According to the official W3C specs , there are dozens of status codes, many of which you’re unlikely to come across.

HTTP Status Codes, HTTP status codes and how to use them in RESTful API or Web Services. List of the five HTTP status code levels HTTP status codes are broken into five different levels. The codes will always be three digits and the first number indicates the level: 1xx Informational response – You won’t really see 1xx level status codes as they’re only a confirmation of a receipt of your request. I think of these as a server

Check Your Website's HTTP Response Status, Any page on a website returns a numerical code that indicates the page's HTTP status. Learn Duration: 7:38 Posted: 16 Sep 2019 To see HTTP status codes with one of these tools, look for the line appearing near the top of the report that says “Status: HTTP/1.1”. This will be followed by the status code that was returned by the server. Understanding HTTP Status Code Classes. HTTP status codes are divided into 5 “classes”.

  • Why the hell would you ever handle such issues on the client? Why don't you get the server to handle these images properly?
  • @Raynos the situation is such: images are created dynamicaly on the server, but it takes a lot of time, which means some of them won't be ready when browser asks for them. At the same time some critical error may occur on the server-side and there will be no image at all. So, based on http status, I have to ask server for images once again, or just inform user, about error.
  • No, your still doing it wrong. You have a HTTP server, when you get an incoming GET request for an image you can "wait" for it to be ready. And if a critical error occured you can return a "critical error" image.
  • @Raynos unfortunately, I'm working only on the front-end, and don't have access for the back-end. I'm not happy with the conditions of the problem. As far as I know server cannot afford keeping lots of open connections, so I can only ask whether image is ready or not, not waiting for the image to be ready.
  • Plugin is not acceptable. AJAX seems to be fine, but what kind of data should I get through AJAX? I can retrieve the image data, but I can't use it to create img element.
  • You would most likely need to send it as a data url. You'll probably need to find some kind of library that can generate data urls on the server side. Then once they arrive it's just a matter of setting the img's src to the data url. This will add a good deal of overhead to loading your images. The real solution is probably to fix the server so it always successfully sends images.
  • Ajax is not a good substitution in case, your wanna-load-images are placed on external domain. Anything new about this issue in 2016?
  • For anyone reading this page, the naturalWidth property is not supported by all browsers. This property is also quite touchy - you should only attempt to read it after the image has loaded. (…) I hope that helps. :)
  • @Axle You are referring to the post from '09. Now it works in all latest browsers version.
  • I happen to work somewhere that makes it a requirement to support older browsers (IE 7 and IE 8 for example). I'm sure there are others out there that suffer a similar fate. Trust me, screaming "Well they should just update their broken tools!" never got me anywhere. :P
  • @Axle Well, there is no IE7 or 8 since upgrade to IE9 is forced. If somebody has older version its mean it is pirate Windows version :- ) Anyway I (and company I'm working for) don't care about anything that is not latest. In fact I only test stuff in Google Chrome, when works is fine.
  • @Axie, Wojciech, img.complete is what you should look at to see if an image is loaded or not, or for guaranteed compatibility you could attach to the onload event.
  • Please note that, from the API for .error(): "The event handler must be attached before the browser fires the error event, which is why the example sets the src attribute after attaching the handler." (emphases mine).
  • just throw some jQuery at it, surely it will solve the problem!