Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Refresh Browsers after new deploy of Angular2 application

Tags:

angular

So I have a couple of clients with browser windows open using my Angular 2 application. I then do an ng build --prod, and publish a new build to the server.

How do I force the clients to refresh all their cached scripts?

like image 789
Shawn de Wet Avatar asked Feb 23 '17 09:02

Shawn de Wet


1 Answers

I just finished implementing a solution for this problem.

I tried a few different approaches but ended up maintaining a separate json file that the application can request on an set interval and compare to the currently loaded version and then act accordingly.

I also played with sw-precache by google and a few other things that I had hoped would just make the problem go away. SW-Precache This looks awesome, but doesn't quite reliably solve our issue since I couldn't find a way to schedule regular checks for invalidating the cache in question.

Gotcha number 1: Add the new file to the assets block in angular-cli.json so that it will be copied into the distribution folder and not included in a built js file, since that would negate the entire point of what we are trying to do.

  "assets": [
    "assets",
    "favicon.ico",
    "web.config",
    "version.json"
  ],

Then I simply created a simple service with a function to request this file, and another to set up and interval to repeatedly call the request. I also opted to use "hard" cache busting on these requests by including a unix timestamp as a query parameter. This may be old school but it makes sure that no matter what or where this is set up you wont get a cached version of the version.json file.

Finally I would recommend some way of keeping this version.json file inline with the version number of your application. A quick search brought me

Versiony on NPM

which after an npm install allows very simple modifications to semantic version numbers. I added some scripts in my package.json to automate making sure the version.json is in line with the package.json before build just to make sure there are no hickups because the code has changed, but the version has not.

like image 166
Sias Mey Avatar answered Nov 01 '22 09:11

Sias Mey