【问题标题】:service worker not loading in offline服务人员未离线加载
【发布时间】:2017-01-18 08:36:12
【问题描述】:

我正在构建一个渐进式 Web 应用,Service Worker 看起来像这样:

CURRENT_CACHE = 'V3'; FILES_TO_CACHE = [ '/index.html', '/js/bcheck.js', '/js/mss.js', '/js/vendor.js' ]; console.info('在文件中'); self.addEventListener('install', function (event) { console.info('已安装'); event.waitUntil(caches.open(CURRENT_CACHE).then(function(cache){ 返回缓存.addAll(FILES_TO_CACHE); })); }); self.addEventListener('activate', function (event) { console.info('激活'); event.waitUntil(caches.keys().then(function (cachesNames) { 返回 Promise.all(cachesNames.map(function (cacheName) { 如果(缓存名称!== CURRENT_CACHE){ 返回缓存。删除(缓存名称); } })) })); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(函数(响应){ // 缓存命中 - 返回响应 如果(响应){ 返回响应; } 返回获取(事件。请求); } ) ); });

我看到安装后我缓存了所有文件,但是当我将服务器离线并重新加载时没有任何效果,就像服务离线并且没有加载一样。

感谢您的帮助

  • 我在 localhost 上使用本地服务器 HTTP

【问题讨论】:

    标签: javascript service-worker


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      对于正常离线工作的 Service Worker,它应该严格地在 Https 中 尝试使用 Https。 并且可以在lighthouse中查看。(LightHouse是查看PWA Service-Worker的工具)。

      【讨论】:

        【解决方案3】:

        你需要告诉你的 Service Worker 在你离线的情况下该怎么做。由于您的 fetch 函数当前已构建,因此它不知道该做什么。尝试这样的事情。您应该能够将其直接复制并粘贴到您的服务工作人员文件中,在浏览器中清除服务工作人员,然后

        `//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');
                }
              })
            })
          );
        }`
        

        【讨论】:

          猜你喜欢
          • 2017-04-17
          • 1970-01-01
          • 2018-10-28
          • 2020-05-31
          • 1970-01-01
          • 2018-10-30
          • 1970-01-01
          • 1970-01-01
          • 2020-11-20
          相关资源
          最近更新 更多