简体   繁体   中英

Using WebP fallback with CSP

I'm using the following to use WebP images with a JPG fallback:

<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.

Is there any way to make this work with the CSP? Worst case scenario, I can enable unsafe-hashes .

Thanks in advance:)

You can use data-... attribute like that:

<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:

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' .

Yes, it's really worst. Safari does not support 'unsafe-hashes' . It's hard to manage a lot of 'hash-values' , all onerror will have an unique one. And after change image name you'll need to recalc and replace hash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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