简体   繁体   中英

Problems cache busting serviceworker index.html file

I'm using Google's SW Precache to generate the serviceworker for an Angular (currently v.4) app hosted on firebase. I'm using Angular cli to generate my distributed files. When it comes time to deploy my app, I use the following commands:

ng build --prod --aot #build angular app
sw-precache --config=sw-precache-config.js --verbose # generate precache
firebase deploy # Send to firebase

My sw-precache-config.js file looks like this:

module.exports = {
  staticFileGlobs: [
    'dist/**.css',
    'dist/**/**.png',
    'dist/**/**.svg',
    'dist/**.js'
  ],
  stripPrefix: 'dist',
  root: 'dist/',
  navigateFallback: '/index.html',
  runtimeCaching: [
    {
      urlPattern: /index\.html/,
      handler: 'networkFirst'
    },
    {
      urlPattern: /\.js/,
      handler: 'cacheFirst'
    }, {
      urlPattern: /fonts\.googleapis\.com/,
      handler: 'fastest'
    },
    {
      default: 'networkFirst'
    }
  ]
};

If I make changes and deploy a new version, I get the cached index.html file even if I refresh or close the browser. I can get the updated index.html file if I add something like ?cachebust=1 to the end of the url. Is there something I'm doing wrong in my process or configuration that is not allowing the latest index.html to be loaded?

As a general best practice, I'd recommend that you explicitly serve your service-worker.js file with HTTP caching disabled, to ensure that changes made to your generated service worker are picked up as expected, without having to wait for the HTTP cached copy to expire.

At some point in the future, the default behavior for Chrome and Firefox will be to always fetch the service worker directly from the network instead of respecting the HTTP cache, but in the meantime, you can read more about the current behavior .

I have a sample configuration for a Firebase deployment that might help:

{
  "hosting": {
    "public": "build",
    "headers": [{
      "source" : "/service-worker.js",
      "headers" : [{
        "key" : "Cache-Control",
        "value" : "no-cache"
      }]
    }]
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM