Search code examples
javascriptjqueryhtmlimageonerror

How can I detect WHY an image failed to load?


I've got an img element on a page with its src being set dynamically on page load (different images for different situations, and the images are provided by clients).

I can detect WHEN an image fails to load and I handle that by reporting it. I also set a placeholder image when it fails to load.

<img alt="Image not found" onError="failedToLoadResource" id="something" class="class1 class2">

This works great. However, just knowing when an image failed to load really isn't enough. I need to be able to identify why it happened. The image is hosted on our server so 404s are unlikely, but not impossible. I don't have access to the client's device and I can't reproduce the issue as described by them.

I've tried looking around but I can't find what I'm looking for...

I'm guessing it might be 404s, some CSP config issue, maybe some internet connection hiccup, whatever. I just want to know what it is, so I can better understand it.

EDIT: Forgot to say the code is in a Cordova app, so there's no log to check.


Solution

  • From the client side, you can try to access image by making an ajax call then parsing the response. Easily done using jQuery.

    var call = $.ajax( "image.img" )
      .fail(function( call, textStatus ) {
        alert( "Request failed: " + textStatus );
      });
    

    From the server side, you can check the server logs, search for the correct request and see what happened. If request never came to the server it might be network/routing/firewall problem.

    Steps to do this, however, are highly dependent on what is used in the backend.