How to prevent Browser cache on Angular 2 site? How to prevent Browser cache on Angular 2 site? angular angular

How to prevent Browser cache on Angular 2 site?


angular-cli resolves this by providing an --output-hashing flag for the build command (versions 6/7, for later versions see here). Example usage:

ng build --output-hashing=all

Bundling & Tree-Shaking provides some details and context. Running ng help build, documents the flag:

--output-hashing=none|all|media|bundles (String)Define the output filename cache-busting hashing mode.aliases: -oh <value>, --outputHashing <value>

Although this is only applicable to users of angular-cli, it works brilliantly and doesn't require any code changes or additional tooling.

Update

A number of comments have helpfully and correctly pointed out that this answer adds a hash to the .js files but does nothing for index.html. It is therefore entirely possible that index.html remains cached after ng build cache busts the .js files.

At this point I'll defer to How do we control web page caching, across all browsers?


Found a way to do this, simply add a querystring to load your components, like so:

@Component({  selector: 'some-component',  templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`,  styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`]})

This should force the client to load the server's copy of the template instead of the browser's.If you would like it to refresh only after a certain period of time you could use this ISOString instead:

new Date().toISOString() //2016-09-24T00:43:21.584Z

And substring some characters so that it will only change after an hour for example:

new Date().toISOString().substr(0,13) //2016-09-24T00

Hope this helps


In each html template I just add the following meta tags at the top:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"><meta http-equiv="Pragma" content="no-cache"><meta http-equiv="Expires" content="0">

In my understanding each template is free standing therefore it does not inherit meta no caching rules setup in the index.html file.