巨大的服务工作者缓存

时间:2018-01-18 16:55:55

标签: javascript caching google-chrome-devtools service-worker progressive-web-apps

我正在开发我的第一个PWA(Progressive Web App)。一切都运作良好,除了离线的东西。我按照许多教程学习如何缓存我的Web应用程序,但我真的很惊讶我的缓存大小。在Chrome开发工具中,我可以看到,在刷新了一些页面之后:

enter image description here

它不断增长! 我想我的“激活”事件的处理存在问题。 这是我的service-worker.js文件:

var dataCacheName = 'heiverage-v1';

var cacheName = 'heiverage-1';
var filesToCache = [
  '/',
  'index.php',
  'spe.php',
  'js/app.js',
  'js/jquery.js',
  'sem.php',
  'main.php',
  'js/script.js',
  'js/bootstrap.js',
  'css/style.css',
  'css/bootstrap.css',
  'img/calculator.png',
  'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css',
  'https://fonts.googleapis.com/css?family=Oxygen',
  'https://fonts.googleapis.com/css?family=Mukta+Mahee:700',
  'css/mainless50.css'
];



self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      console.log('[ServiceWorker] Caching app shell');
      return cache.addAll(filesToCache);
    })
  );
});



self.addEventListener('activate', function(e) {
  console.log('[ServiceWorker] Activate');
  e.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (key !== cacheName && key !== dataCacheName) {
          console.log('[ServiceWorker] Removing old cache', key);
          return caches.delete(key);
        }
      }));
    })
  );
  /*
   * Fixes a corner case in which the app wasn't returning the latest data.
   * You can reproduce the corner case by commenting out the line below and
   * then doing the following steps: 1) load app for first time so that the
   * initial New York City data is shown 2) press the refresh button on the
   * app 3) go offline 4) reload the app. You expect to see the newer NYC
   * data, but you actually see the initial data. This happens because the
   * service worker is not yet activated. The code below essentially lets
   * you activate the service worker faster.
   */
  return self.clients.claim();
});


self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.open('mysite-dynamic').then(function(cache) {
      return cache.match(event.request).then(function(response) {
        var fetchPromise = fetch(event.request).then(function(networkResponse) {
          cache.put(event.request, networkResponse.clone());
          return networkResponse;
        })
        return response || fetchPromise;
      })
    })
  );
});

非常感谢你的帮助!

0 个答案:

没有答案