+ 2

Do I use <img>, <object>, or <embed> for SVG files?

Should I use <img>, <object>, or <embed> for loading SVG files into a page in a way similar to loading a jpg, gif or png? What is the code for each to ensure it works as well as possible? (I'm seeing references to including the pointing to fallback SVG renderers in my research and not seeing a good state of the art reference). Thanks for the help in advance.

29th Mar 2018, 12:05 PM
Michelangelo
Michelangelo - avatar
2 Réponses
+ 5
I can recommend the SVG Primer (published by the W3C), which covers this topic: https://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#SVG_in_HTML If you use <object> then you get raster fallback for free*: <object data="your.svg" type="image/svg+xml"> <img src="yourfallback.jpg" /> </object> *) Well, not quite for free, because some browsers download both resources, see Larry's suggestion below for how to get around that. If you want a non-interactive svg, use <img> with script fallbacks to png version (for older IE and android < 3). One clean and simple way to do that: <img src="your.svg" onerror="this.src='your.png'">. This will behave much like a GIF image, and if your browser supports declarative animations (SMIL) then those will play. If you want an interactive svg, use either <iframe> or <object>. If you need to provide older browsers the ability to use an svg plugin, then use <embed>. For svg in css background-image and similar properties, https://modernizr.com/ is one choice for switching to fallback images, another is depending on multiple backgrounds to do it automatically: div { background-image: url(fallback.png); background-image: url(your.svg), none; } Note: the multiple backgrounds strategy doesn't work on Android 2.3 because it supports multiple backgrounds but not svg. An additional good read is this blogpost https://css-tricks.com/svg-fallbacks/ on svg fallbacks.
29th Mar 2018, 12:18 PM
Baraa AB
Baraa AB - avatar