0

当我测试以下代码并转到 chrome devtools 的缓存存储时,它是空的。它一会儿起作用,一会儿改变cacheName它就停止了,不确定它是否相关。

if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker
        .register('sw_cached_pages.js')
        .then(reg => console.log('Service Worker: Registered (Pages)'))
        .catch(err => console.log(`Service Worker: Error: ${err}`));
    });
  }

这是软件本身:

const cacheName = '00001';

const cacheAssets = [
  'accueil.php',
  'js/accueil.js',
  'inc/Headers.php',
  'inc/footer.php'
];

// Call Install Event
self.addEventListener('install', e => {
  console.log('Service Worker: Installed');

  e.waitUntil(
    caches
      .open(cacheName)
      .then(cache => {
        console.log(cache)
        console.log('Service Worker: Caching Files', cache);
        cache.addAll(cacheAssets);
      })
      .then(() => self.skipWaiting())
  );
});

// Call Activate Event
self.addEventListener('activate', e => {
  console.log('Service Worker: Activated');
  // Remove unwanted caches
  e.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cache => {
          if (cache !== cacheName) {
            console.log('Service Worker: Clearing Old Cache');
            return caches.delete(cache);
          }
        })
      );
    })
  );
});

// Call Fetch Event
self.addEventListener('fetch', e => {
  console.log('Service Worker: Fetching');
  e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
});
4

2 回答 2

1

也许原因是您在浏览器的 DevTools 中选中了“禁用缓存”?这就是我遇到类似问题的原因。

于 2021-08-25T21:23:29.077 回答
0

所以问题出在这部分:

// Call Install Event
self.addEventListener('install', e => {
  console.log('Service Worker: Installed');

  e.waitUntil(
    caches
      .open(cacheName)
      .then(cache => {
        console.log(cache)
        console.log('Service Worker: Caching Files', cache);
        cache.addAll(cacheAssets); // <- here
      })
      .then(() => self.skipWaiting())
  );
});

这非常简单:cache.addAll返回一个承诺,而您无需等待。你只需要return在语句之前添加一个cache.addAll,这会将承诺传递给下一个.then().then(() => self.skipWaiting()))。

顺便说一句:更好的解决方案是使用 await,因为它会使它更清晰。它看起来像这样:

e.waitUntil(
  async () => {
    cache = await caches.open(cacheName);
    console.log('Service Worker: Caching Files', cache);
    await cache.addAll(cacheAssets);
    self.skipWaiting();
  }
);

学习 async/await 非常有帮助,并且会使调试变得更容易。

于 2021-04-07T16:32:34.360 回答