简体   繁体   English

将 WebP 回退与 CSP 结合使用

[英]Using WebP fallback with CSP

I'm using the following to use WebP images with a JPG fallback:我正在使用以下内容将 WebP 图像与 JPG 后备一起使用:

<img 
    src="{{ $img_webp_desktop.RelPermalink }}" 
    onerror="this.onerror=null;this.src='{{ $img_jpg_desktop.RelPermalink }}';" 
    loading="lazy"
    height="{{ $img_jpg_desktop.Height }}" 
    width="{{ $img_jpg_desktop.Width }}">

However, with my CSP set to script-src 'self' , the onerror inline script doesn't get executed and the fallback doesn't work.但是,当我的 CSP 设置为script-src 'self'时, onerror内联脚本不会被执行并且回退不起作用。

Is there any way to make this work with the CSP?有什么方法可以让 CSP 使用它吗? Worst case scenario, I can enable unsafe-hashes .最坏的情况,我可以启用unsafe-hashes

Thanks in advance:)提前致谢:)

You can use data-... attribute like that:您可以像这样使用data-...属性:

<img 
    src="{{ $img_webp_desktop.RelPermalink }}" 
    data-src="{{ $img_jpg_desktop.RelPermalink }}" 
    loading="lazy"
    height="{{ $img_jpg_desktop.Height }}" 
    width="{{ $img_jpg_desktop.Width }}">

and then universally add onerror event listeners to all images having data-src attr:然后将onerror事件侦听器普遍添加到所有具有 data-src 属性的图像:

imgList = document.querySelectorAll("img[data-src]");
imgList.forEach( function(img) {
  img.addEventListener( 'error', function(e) {
    e.target.removeEventListener(e.type, arguments.callee);
    e.target.src = e.target.getAttribute("data-src");
    });
  });

Worst case scenario, I can enable 'unsafe-hashes' .最坏的情况,我可以启用'unsafe-hashes'

Yes, it's really worst.是的,这真的是最糟糕的。 Safari does not support 'unsafe-hashes' . Safari 不支持'unsafe-hashes' It's hard to manage a lot of 'hash-values' , all onerror will have an unique one.很难管理大量的'hash-values' ,所有的onerror都会有一个唯一的。 And after change image name you'll need to recalc and replace hash.更改图像名称后,您需要重新计算并替换 hash。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM