javascript - ServiceWorker 无法离线工作

标签 javascript offline service-worker

我有一个简单的 service worker

安装

self.addEventListener('install', function(event) {
  console.log('Service Worker Install...');
  // pre cache a load of stuff:
  event.waitUntil(
    caches.open(CURRENT_CACHES.prefetch)
      .then(function(cache) {
      return cache.addAll([
        '/android-chrome-192x192.png',
        '/android-chrome-512x512.png',
        '/apple-touch-icon.png',
        '/browserconfig.xml',
        '/favicon-16x16.png',
        '/favicon-32x32.png',
        '/favicon.ico',
        '/favicon.png',
        '/mstile-150x150.png',
        '/safari-pinned-tab.svg',
        '/app.css',
        '/bundle.js',
        '/sw.js'
      ])
      .then(function(){
        console.log('Caches added');
      })
      .catch(function(error){
        console.error('Error on installing');
        console.error(error);
      });
    })
  )
});

激活

self.addEventListener('activate', function(event) {
  console.log('Service Worker Activate...');
  // Delete all caches that aren't named in CURRENT_CACHES.
  var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
    return CURRENT_CACHES[key];
  });

  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.map(function(cacheName) {
          if (expectedCacheNames.indexOf(cacheName) === -1) {
            // If this cache name isn't present in the array of "expected" cache names, then delete it.
            console.log('Deleting out of date cache:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

获取

self.addEventListener('fetch', function(event) {
  console.log('Service Worker Fetch...');

  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        if(event.request.url.indexOf('facebook') > -1){
          return fetch(event.request);
        }
        if(response){
          console.log('Serve from cache', response);
          return response;
        }
      return fetch(event.request);
    })
    .catch(function(error){
      console.error('Error on fetching');
      console.error(error);
    })
  );
});

虽然这有效,但我在缓存中看到所有内容都正确缓存:

enter image description here

当我关闭网络并刷新时,我得到: 获取脚本时发生未知错误。对于 service worker。

enter image description here

难道 service worker 应该已经在那里了吗?为什么要重新获取?

最佳答案

在安装步骤中,您必须缓存 //index.html,或者您可以在获取请求后缓存它们:

self.addEventListener('fetch', function(event) {
  console.log('Service Worker Fetch...');

  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        if(event.request.url.indexOf('facebook') > -1){
          return fetch(event.request);
        }
        if(response){
          console.log('Serve from cache', response);
          return response;
        }
        return fetch(event.request)
            .then(response =>
              caches.open(CURRENT_CACHES.prefetch)
                .then((cache) => {
                  // cache response after making a request
                  cache.put(event.request, response.clone());
                  // return original response
                  return response;
                })
            )

关于javascript - ServiceWorker 无法离线工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42333355/

相关文章:

javascript - 在悬停时选择 sibling

Android离线文档不同于在线文档

security - 如何保护允许离线登录的胖客户端的用户密码?

javascript - service worker 启动后主线程的请求挂起

javascript - 如何知道 Service Worker 正在从缓存中检索数据?

javascript - 使用 node.js 的断言引发的测试错误

javascript - 如何创建Hotjar之类的应用程序?

ios - 离线 Fairplay HLS 内容无法播放

angular - 我们如何将 FCM Service Worker 与现有的 Service Worker 一起使用?

javascript - HTML5 Websockets 服务器要求