Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@angular/service-worker not working when offline

I never got the service worker from Angular Mobile Team to work properly and at this point I guess I forgot to enable something, because it never worked since the initial release. Even if it installs and run on Google Chrome (smartphone & desktop) when I go offline it doesn't work anymore, also it randomly crashes after updates.

There is no documentation on how to set it up. So here is how I did it:

  • ng new test-service-worker
  • npm install @angular/service-worker
  • in .angular-cli.json, I add "serviceWorker": true
  • npm build --prod, output ngsw-manifest.json sw-register.b73048fe3d9f8a1e7ae5.bundle.js and worker-basic.min.js. So everything seems ok
  • https://test-service-worker-97321.firebaseapp.com/ the SW installs
  • If I go offline, wait an hour for cache to expire (or simply disable cache), I get a failed to load error, no matter the device I use.

The generated dist directory:

enter image description here


The generated ngsw-manifest.json:

enter image description here


The service worker installed and running: Test available https://test-service-worker-97321.firebaseapp.com/

enter image description here


When I set the chrome devtools options to Offline and Disable cache the service worker doesn't load content anymore. A good example of how it is supposed to work is Twitter, their web app works when Offline and Disable cache are checked.

enter image description here

NB: I created a few apps before with service workers, and they worked properly on Chrome. I don't know what I'm doing wrong here.

like image 546
Ploppy Avatar asked Dec 11 '22 12:12

Ploppy


2 Answers

You have to test your app in offline mode with an explicit mentioning of index.html. I checked https://test-service-worker-97321.firebaseapp.com/index.html - it works fine.

If you wish your app to work in offline without index document mentioned (and for all other routes), you have to set up route redirection

See the example. This custom ngsw-manifest.json will be merged with auto-generated one during the build.

like image 65
Maxim Salnikov Avatar answered Dec 13 '22 22:12

Maxim Salnikov


With Maxim's help, I followed the same path as asking person, managed to add offline capability to the existing static web and deploy it on Firebase. The custom manifest on root folder should look like below, they will eventually be merged with autogenerated manifest:

{
  "routing": {
    "index": "/index.html",
    "routes": {
      "/": {
        "prefix": false
      },
      "/home": {
        "prefix": false
      },
      "/work": { // any routes starting with '/work'
        "prefix": true
      }
    }
  },
  "external": {
    "urls": [
      {
        "url": "https://fonts.googleapis.com/css?family=Quicksand"
      }
    ]
  }
}
like image 24
bob Avatar answered Dec 13 '22 21:12

bob