简体   繁体   中英

@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.j s 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:

在此输入图像描述


The generated ngsw-manifest.json :

在此输入图像描述


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

在此输入图像描述


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.

在此输入图像描述

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.

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.

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"
      }
    ]
  }
}

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