css - 如何在 CSS 图像上设置 crossorigin="anonymous"?
问题描述
我将我的旧网站设置为 PWA。这是一个PHP网站。我所有的站点资产都位于 CDN 上,并且我使用附加到每个站点的路径的版本控制标签。我想对它们使用缓存优先策略。为此,我必须在我的所有资产中添加 crossorigin="anonymous" 以获得 cors 响应而不是不透明的响应。内联图像、css、js 文件很简单,但是有没有办法让 CSS 中引用的图像返回 cors?目前,它们都以不透明的形式返回。
参考设置此设置的 Workbox 网站...
https://developers.google.com/web/tools/workbox/guides/handle-third-party-requests
解决方案
当浏览器期望响应时,您不能使用no-cors
(不透明cors
)响应,反之亦然。这意味着您应该能够no-cors
在服务工作者中拦截传出请求,将其重写为cors
请求,然后缓存该cors
响应,并将其传递给页面以供使用。
您可以使用与您的请求匹配的自定义路由并使用重写请求的自定义插件no-cors
.svg
实施CacheFirst
策略来完成此操作。requestWillFetch
我自己没有对此进行测试,但我认为以下方法可行:
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}],
})
);
您可以使用generateSW
Workbox 构建工具的模式为您创建此路由,配置如下:
{
// ...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...
}],
};
推荐阅读
- r - R在检查字母顺序的列中交换值
- node.js - Heroku 部署后运行 URL 显示应用程序错误
- java - 如何跟踪 Firestore 读/写操作?
- git - VisualStudio 在 Rebase 时会创建非常不必要的合并冲突?
- c# - Azure Blob 存储的文件大小限制?
- kubernetes - 我可以在没有 virtualBox 的情况下在 ubuntu 上安装 minikube 吗?
- url - HAProxy http-request 将特定路径重定向到另一个路径
- android - Retrofit2:保护baseUrl
- python - 从熊猫系列中删除最小值
- python - Python 3 Tkinter:弹出窗口不显示