首页 > 解决方案 > 如何在 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

标签: csscorsprogressive-web-appsservice-workerworkbox

解决方案


当浏览器期望响应时,您不能使用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}],
  })
);

您可以使用generateSWWorkbox 构建工具的模式为您创建此路由,配置如下:

{
  // ...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...
  }],
};

推荐阅读