0

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

Milan Ferus-Comelo
  • 690
  • 1
  • 8
  • 20

1 Answers1

2

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.

granty
  • 7,234
  • 1
  • 14
  • 21