From browser Javascript, how to tell if an image won’t load

Sometimes it’s necessary in Javascript in a browser to find out whether an image object loads correctly. You might do this to check whether a server is responding, or whether it’s blocked by a firewall.

In plain HTML you would load the image like this

   <img src="/maybe.png" />

then look for the browser’s broken-image indicator visually. You can do this same thing with a Javascript program, without cluttering up your user interface.

It’s a little tricky, because using fetch or AJAX won’t always work. Those ways of loading images require CORS support on the server, and many servers don’t handle CORS correctly for images.

This Javascript function loads an image from within a promise, then tells its caller whether the image load succeeded or failed. On failure, it only can tell load failure from timeout: error codes like 403 or 404 aren’t available.

function loadImage(path, timeout) {
    timeout = timeout || 10000;
    return new Promise(function(resolve) {
        try {
            const image = new Image();
            let expireTime = Date.now();
            image.addEventListener("load", function() { resolve(true) });
            image.addEventListener("error",
                function(error) {
                    const endTime = Date.now();
                    if (endTime > expireTime) {
                        resolve("timeout");
                    }
                    console.log(error);
                    resolve("load error " + path);
                });
            image.src = path;
            expireTime = Date.now() + timeout;
        } catch (err) {
            console.log(err);
            resolve("load exception " + path);
        }
    });
}

Call the function like this:

loadImage("/maybe.png")
.then (function (result) {
          if (result === true) /* all is well with that image */
          else {
            /* something failed */ 
            console.log (result);
           }
       });

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *