javascriptjqueryerror-handlingloading-image

Checking for failed image load


In the code below, I'm appending an image tag to a div. When the image is done loading (successfully), I'd like to run other functions before changing the page.

var $img = $("<img src='https://www.example.com/path' />").on('load', function() {
         console.log('img loaded');
         //do other stuff
         window.location = "otherpage.com";
         return true;
    });

    $(".imgContainer").append($img);

This working perfectly in the case where the image actually exists at the URL provided, or when it isn't blocked. (In my case, I'm getting net::ERR_TUNNEL_CONNECTION_FAILED errors when the image is appended due to my network proxy settings. On other networks, it works fine.)

My question is, how can I test for 404 (Not Found) or net::ERR_TUNNEL_CONNECTION_FAILED errors in the .on('load') callback?

Tried checking the responseText, textStatus, req params in the callback, but obviously since the img is never loaded, the callback is never called. CORS not enabled.


Solution

  • Use on('error', handler) for catching 404

    var $img = $("<img src='https://www.example.com/path' />").on('load', function() {
         console.log('img loaded');
    
    }).on('error', function(event){
    
          console.log('img failed to load');
          console.log(event)
    })