虽然当浏览器需要cors 响应时,您不能使用no-cors (opaque) 响应,但通常反过来也可以。这意味着您应该能够在您的服务工作者中拦截传出的no-cors 请求,将其重写为cors 请求,然后缓存cors 响应,并将其传递给页面以使用.
您可以使用与您的 no-cors .svg 请求相匹配的自定义路由来完成此操作,并使用 custom requestWillFetch plugin 重写请求实施 CacheFirst 策略。
我自己没有对此进行测试,但我认为以下方法可行:
import {registerRoute} from 'workbox-routing';
import {CacheFirst} from 'workbox-strategies';
function requestWillFetch({request}) {
return new Request(request, {mode: 'cors'});
}
registerRoute(
({request, url}) => request.mode === 'no-cors' &&
url.pathname.endsWith('.svg'),
new CacheFirst({
plugins: [{requestWillFetch}],
})
);
您可以使用 Workbox 构建工具的generateSW 模式为您创建此路由,配置如下:
{
// ...your other top-level options here...
runtimeCaching: [{
urlPattern: ({request, url}) => request.mode === 'no-cors' &&
url.pathname.endsWith('.svg'),
handler: 'CacheFirst',
options: {
plugins: [{
requestWillFetch: ({request}) => new Request(request, {mode: 'cors'}),
}],
},
}, {
// ...your other runtime caching entries here...
}],
};