How do I know if a resource is in the browser cache?

Asked

Viewed 581 times

7

Is it possible to find out, via Javascript and without any additional HTTP request, whether or not a particular resource is in the browser cache? And if you are, get it too without that requisition?

In my view, when the server sends a "long-term" resource (i.e. a header Expires with a very high value) browser checks - in a second query - if this feature exists in its own cache and its validity has not expired yet, in which case no additional request is made. However, if such a feature is not found or is "expired", the request is made immediately - without giving the programmer a chance to cancel it.

I would like to have a little more control over this process: if the resource is in the cache, use it, otherwise adopt an alternative strategy. This would require a kind of Javascript API to query the state of the cache, I believe, and as far as I know this is not possible - since the browser abstract your programmer cache.

Is there anything - preferably cross-browsers - that meets this requirement? Or perhaps an alternative way to achieve the same result?

Note: I am not interested in solutions involving the local Storage - because that would require taking the resources that are already in cache and save (and manage) a copy of them in this already limited space.

1 answer

2

Although you might want to renege on solutions with Storage location, I think this would be the only alternative to check the cache without generating a request on the server. So below is an idea of how to do, and there is no need to save all the content of the element, just the string src, and in 2mb can put at least 50 thousand.

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

function RegistrarCache(src) {
    if (!VerificarCache(src)) {
        storage.ElementosNoCache += '[' + src + ']';
    }
}

function RemoverCache(src) {
    if (VerificarCache(src)) {
        storage.ElementosNoCache = storage.ElementosNoCache.replace('[' + src + ']', '');
    }
}

function VerificarCache(src) {
    return (storage.ElementosNoCache.indexOf('[' + src + ']', 0) >= 0);
}

function LimparCache() {
    storage.ElementosNoCache = "";
}

The automation of the registry can be done with jquery, see working on Jsfiddle.

  • 1

    Thanks for the suggestion, in fact it is not necessary to save the entire resource in the Storage location to have any benefit (if I save your URL and its expiration date I can tell if it can be cached). Unfortunately, it is a Russian roulette: if the cache is cleared before the time, the registration on the Storge site will not be notified, so I will end up doing yes the request I was trying to avoid. Anyway, +1, because at least this strategy reduces the overhead in relation to "no solution" - even if it is not a definitive solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.