如何使工作箱缓存跨源响应?
How to make workbox cache cross origin responses?
根据workbox doc,应该配置跨域请求以确保正则表达式匹配URL的开头。但是,它不起作用。
Service Worker 代码如下。
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');
workbox.routing.registerRoute(
/.*\.(png|jpg|jpeg|svg|gif)/,
workbox.strategies.cacheFirst()
);
workbox.routing.registerRoute(
new RegExp('^https://a248.e.akamai.net/.*'),
workbox.strategies.cacheFirst()
);
在该页面中,来自同源资源的响应被缓存,但来自 https://a248.e.akami.net
的响应未被缓存。
我的配置有什么问题吗?或者这是工作箱 3.0.0 的错误?
您的 https://a248.e.akami.net
服务器上是否启用了 CORS?如果没有,您将返回 opaque responses,默认情况下,使用 cacheFirst
策略时不会缓存这些内容。
如果您想 opt-in 在使用 cacheFirst
策略时缓存这些响应,可以使用 guide for handling third-party requests 配方:
workbox.routing.registerRoute(
new RegExp('^https://a248.e.akamai.net/.*'),
workbox.strategies.cacheFirst({
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200]
})
]
}),
);
出现这种情况时,在本地主机中使用 Workbox v3 时,您还应该会在 JavaScript 控制台中看到一条新警告,解释发生了什么。
根据workbox doc,应该配置跨域请求以确保正则表达式匹配URL的开头。但是,它不起作用。
Service Worker 代码如下。
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');
workbox.routing.registerRoute(
/.*\.(png|jpg|jpeg|svg|gif)/,
workbox.strategies.cacheFirst()
);
workbox.routing.registerRoute(
new RegExp('^https://a248.e.akamai.net/.*'),
workbox.strategies.cacheFirst()
);
在该页面中,来自同源资源的响应被缓存,但来自 https://a248.e.akami.net
的响应未被缓存。
我的配置有什么问题吗?或者这是工作箱 3.0.0 的错误?
您的 https://a248.e.akami.net
服务器上是否启用了 CORS?如果没有,您将返回 opaque responses,默认情况下,使用 cacheFirst
策略时不会缓存这些内容。
如果您想 opt-in 在使用 cacheFirst
策略时缓存这些响应,可以使用 guide for handling third-party requests 配方:
workbox.routing.registerRoute(
new RegExp('^https://a248.e.akamai.net/.*'),
workbox.strategies.cacheFirst({
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200]
})
]
}),
);
出现这种情况时,在本地主机中使用 Workbox v3 时,您还应该会在 JavaScript 控制台中看到一条新警告,解释发生了什么。