How to prevent Browser cache on Angular 2 site?
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
A combination of @Jack's answer and @ranierbit's answer should do the trick.
Set the ng build flag for --output-hashing so:
ng build --output-hashing=all
Then add this class either in a service or in your app.module
@Injectable()
export class NoCacheHeadersInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const authReq = req.clone({
setHeaders: {
'Cache-Control': 'no-cache',
Pragma: 'no-cache'
}
});
return next.handle(authReq);
}
}
Then add this to your providers in your app.module
:
providers: [
... // other providers
{
provide: HTTP_INTERCEPTORS,
useClass: NoCacheHeadersInterceptor,
multi: true
},
... // other providers
]
This should prevent caching issues on live sites for client machines
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.
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?