1

I wonder if I can use tag <img> like <video>. When I want to add a video to my website I use:

<video>
   <source src="movie.mp4" type="video/mp4">
   <source src="movie.ogg" type="video/ogg">
</video>

The result is that browser loads only first file, which are supported. It's possible to do the same with <img>? I want to add icons in svg and png/jpg format, so browser will loads the one, which support. Or maybe is better to do it with some Javascript to detect user-agent and then replace graphics in other format?

Adam Golab
  • 133
  • 4
  • 9

1 Answers1

3

No, you cannot combine <img> with <source>. It was deliberately not allowed, because it created backwards-compatibility problems. However, for this use case, the new element <picture> was introduced:

<picture>
  <source type="image/svg+xml"
    srcset="image.svg">
  <img src="fallback.jpg" alt="">
</picture>

It is gaining support, but since it's brand-new, some important browsers are missing yet.

Boldewyn
  • 81,211
  • 44
  • 156
  • 212
  • But, how about support? At now `` is only supported in Chrome and Opera. So it's not solution to widely support at this time. – Adam Golab Mar 27 '15 at 19:11
  • You could use a JavaScript polyfill (with [Picturefill](http://scottjehl.github.io/picturefill/) the most popular). This way, you can use the forward-proof mark-up also in older browsers. – Boldewyn Mar 27 '15 at 19:36
  • Ok, thanks :) so JS actually is the one posible and rational way to do it. – Adam Golab Mar 27 '15 at 19:44
  • Well, it depends on your use case. You could load the SVG with an `` and write an `` in it as fallback. However, when you want to use the SVG as icons, this will probably not fit your bill (most likely because of `click` event issues inside the ``). That would be a markup-only solution specifically for the SVG/PNG combo with close to 100% browser support. – Boldewyn Mar 27 '15 at 20:17