仅缓存 Service Worker 内部的图像 [英] Caching only images inside of a service worker

查看:47
本文介绍了仅缓存 Service Worker 内部的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是软件的代码,一切正常.我之前缓存了所有动态页面,但这给我带来了一些问题.用户交互后的页面 DOM 更改不会在下次页面查看时反映出来.始终显示原始 DOM.

Following is the code for the SW, all working fine. I was caching all the dynamic pages previously, but this was creating me some issues. Like page DOM changes after users interaction are not reflected next time page view. Always it shows original DOM.

所以我需要动态缓存唯一的图像.我已经注释了缓存所有内容的原始代码.

SO I have needed the only image caching dynamically. I have commented original code which was caching all content.

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" 文章,并在您的内部使用 request.destinationfetch 处理程序来确定哪些请求将用于图像.

I'd recommend following the approach outlined in this "Service Worker Caching Strategies Based on Request Types" article, and use request.destination inside of your fetch handler to figure out which requests are going to be used for images.

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 部分.

It's possible that a request for an image might be loaded via something like XMLHttpRequest, in which case the request.destination value likely won't be set properly. If that's the case, I'd recommend just checking the portion of the URL you feel is most likely to be unique using string comparisons.

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.
};

这篇关于仅缓存 Service Worker 内部的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆