Post-loading : check if an image is in the browser cache

after some reseach, I found a solution :

The idea is to log the cached images, binding a log function on the images ‘load’ event.
I first thought to store sources in a cookie, but it’s not reliable if the cache is cleared without the cookie. Moreover, it adds one more cookie to HTTP requests…

Then i met the magic : window.localStorage (details)

The localStorage attribute provides
persistent storage areas for domains

Exactly what i wanted :). This attribute is standardized in HTML5, and it’s already works on nearly all recent browsers (FF, Opera, Safari, IE8, Chrome).

Here is the code (without handling window.localStorage non-compatible browsers):

var storage = window.localStorage;
if (!storage.cachedElements) {
    storage.cachedElements = "";
}

function logCache(source) {
    if (storage.cachedElements.indexOf(source, 0) < 0) {
        if (storage.cachedElements != "") 
            storage.cachedElements += ";";
        storage.cachedElements += source;
    }
}

function cached(source) {
    return (storage.cachedElements.indexOf(source, 0) >= 0);
}

var plImages;

//On DOM Ready
$(document).ready(function() {
    plImages = $(".postLoad");

    //log cached images
    plImages.bind('load', function() {
        logCache($(this).attr("src"));
    });

    //display cached images
    plImages.each(function() {
        var source = $(this).attr("alt")
        if (cached(source))
            $(this).attr("src", source);
    });
});

//After page loading
$(window).bind('load', function() {
    //display uncached images
    plImages.each(function() {
        if ($(this).attr("src") == "")
            $(this).attr("src", $(this).attr("alt"));
    });
});

Leave a Comment