qadenza
qadenza

Reputation: 9293

solving cached css and js using localstorage

My clients often complain they can't see my upgraded css or js effect. Problem are cached files.
Maybe this could be the solution:

$(document).ready(function(){
    var a = 0;
    var b = localStorage.getItem('clear');
    if (a !== b) {
        localStorage.setItem('clear', a);           
        window.location.reload(true);
    }
});

Next time when I change css or js var a will be 1.
Next time - 0 again, and so on.

I still didn't test this, but it's simple and should work.
Do you see any downside?

Upvotes: 0

Views: 60

Answers (2)

dani herrera
dani herrera

Reputation: 51655

For me, the clean solution is to include version on url as GET parameter:

<link rel="stylesheet" href="style.css?v=2017-12-29-01">
<script src="script.js?v=2017-12-29-01" type="text/javascript"></script>

It has not side effects and not needed to reload page.

EDITED OP post an interesting link. It seems my approach is not an universal solution. Some proxies may be configured to don't serve this kind of url's from cache:

Revving Filenames: don’t use querystring

The solution is to rev the name, perhaps by including the file’s timestamp or version number in the URL. But which is better: mylogo.1.2.gif or mylogo.gif?v=1.2? To gain the benefit of caching by popular proxies, avoid revving with a querystring and instead rev the filename itself.

The author concludes with:

Proxy administrators can change the configuration to support caching resources with a querystring, when the caching headers indicate that is appropriate. But the default configuration is what web developers should expect to encounter most frequently. ... For those users who are behind proxies, help foster a faster experience by avoiding a querystring for cacheable resources

In this case:

<link rel="stylesheet" href="style-2017-12-29-01.css">
<script src="script-2017-12-29-01.js" type="text/javascript"></script>

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Strict equals seems to be a problem here. Change it to,

if (a != b) {

Or just convert the value retrieved from local storage to a number before doing the comparison.

var b = +(localStorage.getItem('clear'));

Upvotes: 1

Related Questions