首页 > 解决方案 > 服务工作者 skipWaiting 和 clients.claim 在首次加载时未控制浏览器

问题描述

现在我的服务人员看起来像这样:

self.addEventListener('install', event => {
  console.log('V1 installing…')
  self.skipWaiting()

  event.waitUntil(
    caches
      .open('sw-cache')
      .then(cache =>
        cache.addAll([
          '/assets/img/bbcourt-2pt.png',
          '/assets/img/bbcourt-3pt.png'
        ])
      )
  )
})

self.addEventListener('activate', event => {
  self.clients.claim()
  console.log('V1 now ready to handle fetches!')
})

self.addEventListener('fetch', event => {
  const url = new URL(event.request.url)

  if (
    url.origin == location.origin &&
    url.pathname == '/assets/img/bbcourt-2pt.png'
  ) {
    event.respondWith(caches.match('/assets/img/bbcourt-2pt.png'))
  }

  if (
    url.origin == location.origin &&
    url.pathname == '/assets/img/bbcourt-3pt.png'
  ) {
    event.respondWith(caches.match('/assets/img/bbcourt-3pt.png'))
  }
})

目前,我正在尝试使用 self.skipWaiting() 和 self.clients.claim() 立即通过该服务人员控制浏览器,这样即使我使用 bbcourt-2pt.png 和 bbcourt- 3pt.png 在第一次加载时离线时,缓存的图像仍然由 service worker 提供。但是,服务人员似乎还没有接管第一次加载。我究竟做错了什么?

标签: javascriptionic-frameworkservice-worker

解决方案


推荐阅读