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

Caching 仅缓存服务工作者内部的图像,caching,service-worker,progressive-web-apps,Caching,Service Worker,Progressive Web Apps,以下是SW的代码,所有工作正常。我以前缓存了所有动态页面,但这给我带来了一些问题。像页面DOM一样,用户交互后的更改不会在下次查看页面时反映出来。它总是显示原始DOM 因此,我需要唯一的动态图像缓存。我已经评论了缓存所有内容的原始代码 self.addEventListener('activate', function(event) { console.log('[Service Worker] Activating Service Worker ....', event); /*eve

以下是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);
        }
      })
  );
});

我建议遵循这篇“”文章中概述的方法,在
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.
};

你的问题是什么?:)@帕特,我需要动态缓存图像,我希望它能工作,而这一个又是你的敌人。希望你有答案。