Search code examples
htmlsvgjpegwebpfallback

<picture> equivalent for fallback from webp to jepg


I have the following classic SVG code:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100">
  <image 
    xlink:href="foo.webp"
    height="100"
    width="100"
    x="0"
    y="0"
    image-rendering="optimizeQuality"
  />
</svg>

However, on some browsers, webp is not yet supported (iOS and macOS I am looking at you: https://caniuse.com/?search=webp) ...

So, is there a way similar to the <picture> element to do something like this (syntax obviously wrong, but I hope it does convey the idea):

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100">
  <image 
    xlink:href="foo.webp"
    height="100"
    width="100"
    x="0"
    y="0"
    image-rendering="optimizeQuality"
  />
  <fallback_to>
  <image 
    xlink:href="foo.jpg"
    height="100"
    width="100"
    x="0"
    y="0"
    image-rendering="optimizeQuality"
  />
</svg>

... without of course getting the double-http-hit problem. And without using client-side Javascript (modernizr or other).

Many thanks!


Solution

  • Maybe you could use <foreignObject>. Inside the element you can specify the HTML that you need, like the <picture> element.

    <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" width="400">
      <foreignObject x="0" y="0" width="300" height="200">
        <picture xmlns="http://www.w3.org/1999/xhtml">
          <source srcset="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a1/Johnrogershousemay2020.webp/200px-Johnrogershousemay2020.webp" type="image/webp">
          <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a1/Johnrogershousemay2020.webp/200px-Johnrogershousemay2020.webp.png" alt="logo">
        </picture>
      </foreignObject>
    </svg>