Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 disable browser caching

I am using angular2 for web development, and Jenkins for continuous integration, when i release code at the end of every sprint, it gets deployed on CI Server.

But, when users load the UI, they do not get the new UI changes by default, they have to clear the cache ( I do not want users to clear the cache or disable there cache just for this UI)

How can I handle programatically for the browser to not cache old files and reload the new changes by default (atleast in development)

Note: I presently set:

import { enableProdMode } from '@angular/core';
enableProdMode();

None of the documentation states this to be the reason and removing it does not help either.

like image 982
user1933888 Avatar asked Feb 19 '26 00:02

user1933888


1 Answers

Two popular ways of accomplishing this "cache busting" are:

  1. Using a query string on the end of your file request that gives a version number. For example, when you create a javascript file you would name it "my-file.js". Then in your HTML you would request it as:

<script type="text/javascript" src="my-file.js?v=1.0.0"></script>

When you make some changes to your file you update your request to:


<script type="text/javascript" src="my-file.js?v=1.0.1"></script>

You can use whatever query string you want as long as you change it. The browser sees it as a different file, but it should have no effect on what file your server sends as a response.

  1. If you are using a bundler like webpack or systemJS they can automatically include a hash as part of the file name. This hash can change based on the file contents so that when the contents change the file name changes and thus the file is no longer cached. The caveat with this is that you need to update the file name you are requesting in your HTML. Again, most tools have a way to automatically do this for you.

A webpack example config to accomplish this is:

output: {
        path: 'dist',
        publicPath: '/',
        filename: 'js/[name].[chunkhash].js'
    },

and then use the HtmlWebpackPlugin to auto-generate your index.html with the correct file names injected (with inject: true):

 plugins: [
            new HtmlWebpackPlugin({
                filename: '../index.html',
                template: './index.html',
                inject: true
            }), ...

More info on webpack file naming:

https://github.com/webpack/docs/wiki/Configuration#output

More info on html webpack plugin:

https://github.com/ampedandwired/html-webpack-plugin#basic-usage

like image 115
dmungin Avatar answered Feb 20 '26 17:02

dmungin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!