【问题标题】:How to set crossorigin="anonymous" on CSS images?如何在 CSS 图像上设置 crossorigin="anonymous"?
【发布时间】:2021-04-29 18:06:58
【问题描述】:

我正在将我的旧网站设置为 PWA。这是一个PHP网站。我所有的站点资​​产都位于 CDN 上,并且我使用附加到每个站点的路径的版本控制标签。我想对它们使用缓存优先策略。为此,我必须在我的所有资产中添加 crossorigin="anonymous" 以获得 cors 响应而不是不透明的响应。内联图像、css、js 文件很简单,但是有没有办法让 CSS 中引用的图像返回 cors?目前它们都以不透明的形式返回。

Workbox 的网站,参考设置...

https://developers.google.com/web/tools/workbox/guides/handle-third-party-requests

【问题讨论】:

    标签: css cors progressive-web-apps service-worker workbox


    【解决方案1】:

    虽然当浏览器需要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...
      }],
    };
    

    【讨论】:

    • 这可以使用 GenerateSW() 吗?
    • 是的,我添加了一个示例配置。
    猜你喜欢
    • 2022-11-04
    • 2015-10-17
    • 1970-01-01
    • 2018-09-05
    • 2020-10-04
    • 2022-11-15
    • 2017-06-08
    • 2017-05-29
    • 2011-03-09
    相关资源
    最近更新 更多