【问题标题】:Caching only images inside of a service worker仅在服务人员内部缓存图像
【发布时间】:2020-03-23 13:45:54
【问题描述】:

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

【问题讨论】:

  • 您的问题是什么? :)
  • @pate 我需要动态缓存图片

标签: caching service-worker progressive-web-apps


【解决方案1】:

我建议遵循这篇“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.
};

【讨论】:

猜你喜欢
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 2018-08-16
  • 2014-05-12
  • 1970-01-01
  • 2018-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多