首页 > 解决方案 > PWA 有时看起来很破旧,直到页面重新加载

问题描述

我在这里制作了一个渐进式网络应用程序来练习数学:https ://www.mathmammoth.com/practice/

问题是,有时它开始看起来很破旧,直到我重新加载页面。要重现此问题,请转到该页面。它现在看起来很好,但是当你重新加载它时,它看起来真的很破旧——CSS 和 JavaScript 不知何故无法加载。它还会闪烁此“无法访问此站点”错误(它可能会在您的浏览器中显示不同的内容,这仅适用于 Chrome)。这只发生在您第一次访问该页面时。它可能发生在不同的时间,我认为当我更换服务人员时也会发生。

这是服务工作者文件:

var CACHE_VERSION = 48;
var CACHE_STATIC_NAME = 'static-v' + CACHE_VERSION;
var CACHE_DYNAMIC_NAME = 'dynamic-v' + CACHE_VERSION;

self.addEventListener('install', function(event) {
  self.skipWaiting();
  console.log(
    '[Service Worker] Installing Service Worker ...',
    event
  );
  event.waitUntil(
    caches.open(CACHE_STATIC_NAME).then(function(cache) {
      console.log('[Service Worker] Precaching App Shell...');
      cache.addAll([
        '/practice/',
        '/practice/favicon.ico',
        '/practice/index.php',
        '/practice/practice.css',
        '/practice/multiply-with-zeros.php',
        '/practice/exponents.php',
        '/practice/divide-numbers-ending-in-zeros.php',
        '/practice/multiplication.php',
        '/practice/fact-families.php',
        '/practice/addition-single-digit.php',
        '/practice/addition-subtraction-two-digit.php',
        '/practice/factorfind.php',
        '/practice/division.php',
        '/practice/division-remainder.php',
        '/practice/app.js',
        '/practice/bootstrap.min.css',
        '/practice/bootstrap.min.js',
        '/practice/jquery-3.3.1.min.js'
      ]);
    })
  );
});

self.addEventListener('activate', function(event) {
  console.log(
    '[Service Worker] Activating Service Worker ....',
    event
  );
  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(
        keyList.map(function(key) {
          if (key != CACHE_STATIC_NAME && key != CACHE_DYNAMIC_NAME) {
            console.log(
              '[Service Worker] Removing old cache...',
              key
            );
            return caches.delete(key);
          }
        })
      );
    })
  );
  return self.clients.claim();
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches
      .match(event.request)
      .then(res => {
        if (res) {
          return res;
        } else {
          return fetch(event.request)
            .then(function(res) {
              caches.open(CACHE_DYNAMIC_NAME).then(function(cache) {
                cache.put(event.request, res.clone());
                return res;
              });
            })
            .catch(function() {});
        }
      })
      .catch(() => {
        return fetch(event.request)
          .then(function(res) {
            caches.open(CACHE_DYNAMIC_NAME).then(function(cache) {
              cache.put(event.request, res.clone());
              return res;
            });
          })
          .catch(function() {});
      })
  );
});

标签: service-workerprogressive-web-apps

解决方案


推荐阅读