angular app with service-worker (pwa) is not working as expected

1.5k views Asked by At

Working on an offline angular with service workers get the reference from https://angular.io/guide/service-worker-config

Application working fine offline the only issue is with cache update mechanism if i use "installMode": "prefetch" application works fine offline but files in cache never update on updation of the files on server . If i use "installMode": "lazy"` app does not work offline.

below is the ngsw-config.json of my application.

{
  "$schema": "./node_modules/@angular/service-worker/config/schema.json",
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/*.css",
          "/*.js",
          "/*.manifest",
           "/assets/**"
        ]
      }
    } 
  ]
}

also tried updateMode but still cache files not update on changes

  "installMode": "prefetch",
  "updateMode": "prefetch",
1

There are 1 answers

0
Julius Dzidzevičius On

Using lazy for index.html and other small files usually is not needed as these files are very light weight. I would recommend to split assets and other heavy files to a separate group in service worker config file and use lazy only for them:

  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/*.css",
          "/*.js"
        ]
      }
    },
    {
      "name": "app2",
      "installMode": "lazy",
      "resources": {
        "files": [
           "/assets/**"
        ]
      }
    }
  ]
}

Then look at the dist folder after you build your app. It will have a service worker configuration file created based on rules you wrote in ngsw-config.json (it will hold a list of all cached files with hash keys). Try to exclude that file from being cached, by adding explanation mark at the start:

  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "!/some-file-not-to-cache.js"
        ]
      }
    },