【问题标题】:Using a URL query parameter to version cached responses使用 URL 查询参数来版本缓存响应
【发布时间】:2019-09-11 22:33:35
【问题描述】:

我正在尝试缓存特定的 url,每个 url 都有 md5 哈希,如果 url 用新的 md5 更新,我想删除当前的缓存并添加新的缓存。 缓存网址:http://www.mysite.lo/cards/index.php?md5=f51c2ef7795480ef2e0b1bd24c9e07

function shouldFetch(event) {
  if ( event.request.url.indexOf( '/cards/') ==  -1 ) {
    return false;
  }
  return true;
}



self.addEventListener('fetch', function(event) {
  if (shouldFetch(event)) {
    event.respondWith(    
          caches.match(event.request).then(function(response) {
              if (response !== undefined) {
                return response;
              } else {
                return fetch(event.request).then(function (response) {
                  let responseClone = response.clone();

                  caches.open('v1').then(function (cache) {
                    cache.put(event.request, responseClone);
                  });
                  return response;
                }).catch(function (err) {
                  return caches.match(event.request);
                });
              }
        })
    );
}
});

我知道我们可以使用 caches.delete() 等等,但我只想在 md5 从新请求更新时调用它。 谢谢

【问题讨论】:

    标签: caching service-worker


    【解决方案1】:

    您可以通过以下方式大致完成您描述的事情,它在调用cache.matchAll()时使用ignoreSearch option

    self.addEventListener('fetch', (event) => {
      const CACHE_NAME = '...';
    
      const url = new URL(event.request.url);
      if (url.searchParams.has('md5')) {
        event.respondWith((async () => {
          const cache = await caches.open(CACHE_NAME);
          const cachedResponses = await cache.matchAll(url.href, {
            // https://developers.google.com/web/updates/2016/09/cache-query-options
            ignoreSearch: true,
          });
    
          for (const cachedResponse of cachedResponses) {
            // If we already have the incoming URL cached, return it.
            if (cachedResponse.url === url.href) {
              return cachedResponse;
            }
            // Otherwise, delete the out of date response.
            await cache.delete(cachedResponse.url);
          }
    
          // If we've gotten this far, then there wasn't a cache match,
          // and our old entries have been cleaned up.
          const response = await fetch(event.request);
          await cache.put(event.request, response.clone());
    
          return response;
        })());
      }
    
      // Logic for non-md5 use cases goes here.
    });
    

    (您可以通过重新排列一些缓存操作代码以使其脱离关键响应路径,从而使事情变得更加高效,但这是基本思想。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 2017-04-25
      • 1970-01-01
      • 2022-11-30
      • 2017-06-21
      • 1970-01-01
      • 2022-01-24
      相关资源
      最近更新 更多