仅缓存服务工作者内部的图像

Caching only images inside of a service worker

以下是 SW 的代码,一切正常。我之前缓存了所有动态页面,但这给我带来了一些问题。用户交互后页面 DOM 的变化不会反映在下次页面视图中。总是显示原始 DOM.

所以我只需要动态缓存图像。我评论了缓存所有内容的原始代码。

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(function(response) {
        if (response) {
          return response;
        } else {
          /*return fetch(event.request)
            .then(function(res) {
              return caches.open(CACHE_DYNAMIC_NAME)
                .then(function(cache) {

                    /!*if ( event.request.url.indexOf( 'maps.google' ) !== -1 ) {
                        return false;
                    }*!/
                    if (!/^https?:$/i.test(new URL(event.request.url).protocol)) {
                        return;
                    }

                    cache.put(event.request.url, res.clone());
                    return res;
                })
            })
            .catch(function(err) {

                console.log('show offline page as cashe and network not available')
                return caches.open(CACHE_STATIC_NAME)
                    .then(function (cache) {
                        return cache.match(OFFLINE_URL);
                    });
            });*/

            return fetch(event.request);
        }
      })
  );
});

我建议遵循这篇“Service Worker Caching Strategies Based on Request Types”文章中概述的方法,并在 fetch 处理程序中使用 request.destination 来确定将使用哪些请求图片。

self.addEventListener('fetch', (event) => {
  if (event.request.destination === 'image') {
    event.respondWith(/* your caching logic here */);
  }

  // If you don't call event.respondWith() for some requests,
  // the normal loading behavior will be used by default.
};

图像请求可能会通过类似 XMLHttpRequest 的方式加载,在这种情况下,request.destination 值可能无法正确设置。如果是这种情况,我建议您只检查 URL 中您认为最有可能使用字符串比较唯一的部分。

self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url);
  if (url.origin.includes('maps.google')) {
    event.respondWith(/* your caching logic here */);
  }

  // If you don't call event.respondWith() for some requests,
  // the normal loading behavior will be used by default.
};