离线时Service Worker未加载

4
我正在构建一个渐进式Web应用程序,服务工作者代码如下:
    CURRENT_CACHE = 'V3';
    FILES_TO_CACHE = [
        '/index.html',
        '/js/bcheck.js',
        '/js/mss.js',
        '/js/vendor.js'
    ];
console.info('in file'); self.addEventListener('install', function (event) { console.info('installed'); event.waitUntil(caches.open(CURRENT_CACHE).then(function(cache){ return cache.addAll(FILES_TO_CACHE); })); }); self.addEventListener('activate', function (event) { console.info('activated'); event.waitUntil(caches.keys().then(function (cachesNames) { return Promise.all(cachesNames.map(function (cacheName) { if (cacheName !== CURRENT_CACHE) { return caches.delete(cacheName); } })) })); });
self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit - return response if (response) { return response; }
return fetch(event.request); } ) ); });
我注意到在安装后,所有文件都已被缓存。但是,当我将服务器脱机并重新加载页面时,似乎服务脱机了,没有任何内容被加载。
谢谢您的帮助。
  • 我使用本地HTTP服务器localhost。
3个回答

3

你可能正在尝试访问 localhost:port/,但是缓存了 /index.html。尝试访问 localhost:port/index.html,或在serviceWorker代码的FILES_TO_CACHE中添加这个/ 并重试。


1
为了使Service Worker在离线情况下正常工作,它应该严格处于HTTPS状态。尝试使用HTTPS。此外,您可以在Lighthouse上进行验证。(Lighthouse是用于检查PWA Service Worker的工具)。

本地主机上的Http请求已经被允许用于服务工作者。只有在部署到服务器时才需要Https请求。 - Sean McMillan

1

您需要告诉Service Worker在离线情况下该做什么。当前,您的获取函数并不知道该怎么做。尝试使用以下代码。您应该能够直接复制粘贴到Service Worker文件中,在浏览器中清除Service Worker,然后...

`//Borrowed from https://github.com/TalAter/UpUp
function onFetch(event) {
  event.respondWith(
    // try to return untouched request from network first
    fetch(event.request).catch(function() {
      // if it fails, try to return request from the cache
      return caches.match(event.request).then(function(response) {
        if (response) {
          return response;
        }
        // if not found in cache, return default offline content for navigate requests
        if (event.request.mode === 'navigate' ||
          (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
          console.log('[Serviceworker]', "Fetching offline content", event);
          return caches.match('/index.html');
        }
      })
    })
  );
}`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接