Reputation: 14398
I have a MEAN stack website (single page application) and make sure static files get cached by the browser like so:
var app = express(); //express server
app.use(express.static(__dirname + "/public", { maxAge: 86400000*30 }));
app.get("*", function(req, res){ res.sendFile(__dirname + "/public/index.html"); });
Now in my index.html
I link to my CSS and JS files normally like so:
<link rel="stylesheet" type="text/css" href="/framework/css/main.min.css?version=1.9">
<script type="text/javascript" src="/framework/js/min/app.min.js?version=1.7"></script>
Notice the version control numbers at the end of the filenames. Now, if I update the CSS or JS, I just upload my new files and change the version control number. This should update the cache (and does) on a page refresh.
The problem is, if the user simply visits the site again (and doesn't hit refresh) or if they had visited the site on a mobile and without shutting the browser down, simply opened it up again on another day, they don't get the new files - they get the cached versions.
This is causing all sorts of issues for me. Is there a way to force the new files to be served and cached when an update is made? I make updates once every 1 or 2 weeks and for site speed, I want files to be cached during this time.
Upvotes: 0
Views: 2344
Reputation: 17168
You can use the Page Visibility API to detect when the user comes back to your page. You can then refresh it manually if so much time has passed.
var hasBeenXDays = (function(){
var offset = Date.now();
var day = 1000 * 60 * 60 * 24;
return function(s){
return day*s + offset <= Date.now();
};
})();
document.addEventListener("visibilitychange", function handleVisibilityChange() {
if (!document.hidden && hasBeenXDays(14)) {
window.location.reload(true);
}
}, false);
Upvotes: 0
Reputation: 3730
Google Inbox gives a small notification to "Please refresh your page - there is a new version available".
Maybe you should try that approach.
Reloading dynamically is not a piece of cake... Have a look at these as well
Is there an easy way to reload css without reloading the page?
Dynamically reload local Javascript source / json data
Upvotes: 1
Reputation: 48
It won't keep cached even on a simple refresh with changed filenames. I even think it is not quite simple to handle, especially with reloading JS stuff, libraries and so on...
My Chrome Mobile Browser refreshes sites even without my interest, just because last call was e.g. one day ago.
Upvotes: 0