Ensure loading of background images using jQuery

I have a system that uses a set of other integration points, specifically reading images from the other system and requires login. If the cookie expires for the other system then I must reload my page to force a new login.

There are no events triggered for background image loading in the DOM so I need to check the loading specifically. To do this, I run the following method when loading new content to the page, in this case with AJAX.

function ensureImages(nodes, limit) {
    /// <summary>
    /// Checks that all our images are loaded correctly. Reload the page if this happens.
    /// </summary>
    /// <param name="nodes">The nodes to check.</param>
    /// <param name="limit">The error limit.</param>

    // Do not try this twice
    if (location.href.indexOf("?reload") > -1) {
        return;
    }

    var tested = 0;
    var errors = 0;

    // Grab the elements to check and loop them
    nodes.each(function() {

        // Send max double the amount if images to test 
        // so a fail is that 50% of loaded images cannot load
        if (tested >= limit * 2) {
            // Do not test any more
            return;
        }

        // Get image source
        var image = $(this).attr("style");
        if (!image) {
            return;
        }

        image = image.split("'")[1];

        // Wait for image to test load
        tested++;
        testImage(image).then(function(result) {

            if (!result) {
                errors ++;
            }

            if (errors === limit) {
                // We have a problem, reload page
                location.href = location.href.split("?")[0] + "?reload";
            }
        });
    });
}

You might want to display an error message or replace the images, but this is a start. To test the actual image, I use the background URL and load the image into memory. If then report back if it worked or not.

function testImage(url) {
    /// <summary>
    /// Tests an image by loading it in memory.
    /// </summary >

    var dfd = $.Deferred();

    $("<img/>")
        .on("load", function() { dfd.resolve(true); })
        .on("error", function() { dfd.resolve(false); })
        .attr("src", url);

    return dfd;
}

You can then check that backgrounds are loaded into the node using:

ensureImages($(".dynamic.result .img-holder"), 3);

Hope this helps!