@angular/service-worker not working when offline

╄→尐↘猪︶ㄣ 提交于 2019-12-18 06:48:36

问题


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:


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/43029667/angular-service-worker-not-working-when-offline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!