Roman Dużynski
Roman Dużynski

Reputation: 63

Angular2 force/hard reload of browser cached scripts?

I know that there are a lot of posts about that in web, but none of them satisfied me. Most of people recommends appending a verizon number to each script/css file. But this sound like a lot of job to me (project is qute bit), maybe there is some way to version only output files, some CLI command I dont know?

My solution was based of simple pinging to API for new version number, when > than stored then reload the page. And here is a tricky part - even location.reload(true) does not refresh the cached angular stuff. Manually CTRL+SHIFT+R does this job nicely. This would be good enough for me if the programmaticly hard reload would work.

I also tried a this.compiler.clearCache(); but also with no effect.

Thanks in advance! :)

Upvotes: 2

Views: 5040

Answers (2)

Tomasz Kula
Tomasz Kula

Reputation: 16857

The @angular/cli does the cache busting for you. It appends the hash to script/css file names if you run the ng build with the --prod flag.

ng build

Upvotes: 5

Chirag Ravindra
Chirag Ravindra

Reputation: 4830

EDIT: If you are using the angular-cli, the @Tomasz's answer is probably better than the methods listed below.

Ideally you would use a module bundler like Webpack or a task runner like Grunt to automatically 'fingerprint' your files (ie, append a unique identifier to the file name based on it's contents).

But if that is not an option, a simple hack would be to :

  1. set the caching headers on your HTML to avoid caching on the browser
  2. Append a random query parameter to your script tag URLs in your HTML which you can change each time you want a new version.

<script src='/js/some.js?v=1.1.3'></script>

Changing the random query parameter (v in the example) will ensure the browser makes a fresh request as the URL is different than the cached (older) version

Upvotes: 2

Related Questions