1

I'm trying to set up a service worker using sw-precache to cache assets from CDNJS to be used offline. Unfortunately, this doesn't seem to be working. Here's what I have so far:

Before any of the scripts are loaded in index.html:

<script type='text/javascript'>
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/js/service_worker.js')
      .then(function() {
        console.log("Service Worker Registered")
      })
  }
</script>

And here's the Gulp task I'm using to generate the service worker:

const config = require('../config')
const gulp = require('gulp')
const swPrecache = require('sw-precache')

gulp.task('serviceWorker', (callback) => {

  swPrecache.write(config.build.serviceWorker, {
    runtimeCaching: [
      {
        urlPattern: /^https:\/\/cdnjs\.cloudflare\.com/,
        handler: 'networkFirst'
      }
    ]
  }, callback)
})

When I run the app, I see Service Worker Registered logged to the console. However, if I disconnect my wifi the app fails to loads the scripts. What am I doing wrong?

Errors

4

2 回答 2

5

您正在某个 JS 路径上注册服务工作者/js/service_worker.js。这里的范围限制服务工作者只控制该路径下的指定内容/js/

I suggest you to register service worker at root level即 www.example.com/ 然后您可以控制在此域下提供的所有页面。

于 2016-06-30T09:19:43.423 回答
0

我认为您的问题与范围有关。

Service Worker 仅具有其所在目录的最大范围。也就是说,它无法加载从其结构或之上的位置拉出的文件/请求/响应,只能在下面。

因此,如果您将 Service Worker 的位置更改为 Web 项目的根目录,则应该触发 fetch 事件并且您的资产应该从缓存中加载。

这在“注册服务工作者”部分中进一步解释。https://developers.google.com/web/fundamentals/getting-started/primers/service-workers

于 2018-03-28T12:04:34.793 回答