1

I am looking for a solution to show different types of images based on the browser type. I want to show png files in case the browser is safari and webp files in case the browser is not safari.

I think this thread already delivers the right js code: How to detect Safari, Chrome, IE, Firefox and Opera browser?

// Safari 3.0+ "[object HTMLElementConstructor]" 
var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));

How can I call the result in a hugo if statement?

Somehow like this:

{{ $safari := isSafari }}
{{ if eq safari true }}
  <img src="{{ "img/bannerphone.png" | absURL }}" alt="phone">
{{ else }}
  <img src="{{ "img/bannerphone.webp" | absURL }}" alt="phone">
{{ end }}

Thanks and Regards

jakerupp11
  • 43
  • 5
  • 1
    Use the picture element instead and show the webp image if the browser says it supports it. That way Safari will automaticly start using webp if they get support for it. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture – Karl-Johan Sjögren Sep 09 '20 at 11:59
  • @Karl-JohanSjögren - what a great solution! Thanks you so much!!! – jakerupp11 Sep 09 '20 at 18:03

1 Answers1

1

JS is executed only after website is loaded in browser. Hugo is executed beforehand. There is no way to achieve this in build process. You have to deal with img src switching on frontend, or better to use img cdn like cloudinary...

zabatonni
  • 69
  • 5