简体   繁体   English

CDN服务人员

[英]CDN Service Worker

I'm trying to set up a service worker using sw-precache to cache assets from CDNJS to be used offline. 我正在尝试使用sw-precache设置服务工作者,以从CDNJS缓存资产以供离线使用。 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 : 在将任何脚本加载到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: 这是我用来生成服务工作者的Gulp任务:

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. 运行应用程序时,我看到已Service Worker Registered登录到控制台。 However, if I disconnect my wifi the app fails to loads the scripts. 但是,如果我断开wifi,则该应用无法加载脚本。 What am I doing wrong? 我究竟做错了什么?

失误

You are registering service worker at some JS path /js/service_worker.js . 您正在某个JS路径/js/service_worker.js上注册服务工作者。 Here scope constrains the service worker to only control the specified contents under that path /js/ . 这里范围限制了服务工作者仅控制该路径/js/下的指定内容。

I suggest you to register service worker at root level ie www.example.com/ then you are able to control all pages that being served under this domain. I suggest you to register service worker at root level即www.example.com/) I suggest you to register service worker at root level这样您就可以控制在该域下提供服务的所有页面。

I think your issue is with scoping . 我认为您的问题在于范围界定

Service worker only has a maximum scope of the directory it is in. That is to say, it can't load files/requests/responses that are pulled from a location at or above its structure, only below. Service Worker仅具有其所在目录的最大范围。也就是说,它无法加载从其结构或更高结构(仅在其下方)位置提取的文件/请求/响应。

Therefore, if you change the location of your service worker to the root of your web project, the fetch event should fire and your assets should load from cache. 因此,如果将服务人员的位置更改为Web项目的根目录,则将触发fetch事件,并且应从缓存加载资产。

This is further explained here, in the "Register A service worker" section. 在“注册A服务工作者”部分中对此进行了进一步说明。 https://developers.google.com/web/fundamentals/getting-started/primers/service-workers https://developers.google.com/web/fundamentals/getting-started/primers/service-workers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM