caching - 使用工作箱时如何忽略缓存网址中的网址查询字符串?

标签 caching fetch service-worker progressive-web-apps workbox

有没有办法使用 workbox 忽略来自注册路由下方的查询字符串“?screenSize=”!如果我可以使用正则表达式,我将如何在下面的场景中编写它?基本上,无论 screenSize 查询字符串是什么,我都希望匹配缓存。

workboxSW.router.registerRoute('https://example.com/data/image?screenSize=980',
workboxSW.strategies.cacheFirst({
    cacheName: 'mycache',
    cacheExpiration: {
        maxEntries: 50
    },
    cacheableResponse: {statuses: [0, 200]}
})
);

尝试使用 cachedResponseWillBeUsed 插件后: 我没有看到插件已应用: enter image description here

最佳答案

更新:从 Workbox v4.2.0 开始,新的 cacheKeyWillBeUsed 生命周期回调可以帮助覆盖读取和写入操作的默认缓存键:https://github.com/GoogleChrome/workbox/releases/tag/v4.2.0

原始回复:

你应该可以通过写一个 cachedResponseWillBeUsed plugin 来做到这一点你在配置策略时传入的:

// See https://workboxjs.org/reference-docs/latest/module-workbox-runtime-caching.RequestWrapper.html#.cachedResponseWillBeUsed
const cachedResponseWillBeUsed = ({cache, request, cachedResponse}) => {
  // If there's already a match against the request URL, return it.
  if (cachedResponse) {
    return cachedResponse;
  }

  // Otherwise, return a match for a specific URL:
  const urlToMatch = 'https://example.com/data/generic/image.jpg';
  return caches.match(urlToMatch);
};

const imageCachingStrategy = workboxSW.strategies.cacheFirst({
  cacheName: 'mycache',
  cacheExpiration: {
      maxEntries: 50
  },
  cacheableResponse: {statuses: [0, 200]},
  plugins: [{cachedResponseWillBeUsed}]
});


workboxSW.router.registerRoute(
  new RegExp('^https://example\.com/data/'),
  imageCachingStrategy
);

关于caching - 使用工作箱时如何忽略缓存网址中的网址查询字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46281732/

相关文章:

javascript - ServiceWorker 的冗余状态应该怎么办?

javascript - Angular js - $http 缓存时间?

javascript - 'fetch' 方法是否提供与 'FileReader' 相同的功能?

javascript - ReactJS Fetch POST 导致不需要的刷新

javascript - 获取 POST 在 Edge v42+ 中不起作用

javascript - 了解 Chrome 中 Service Worker 缓存文件的时间统计信息

css - Symfony2,加载没有缓存的css文件

python - 如何在django中利用浏览器缓存

php - 在 MAMP 服务器上安装 APCu

javascript - 如何缓存 bust sw-toolbox?