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 mimetype or pointing to fallback SVG renderers in my research and not seeing a good state of the art reference).
Assume I am checking for SVG support with Modernizr and falling back (probably doing a replacement with a plain <img>
tag)for non SVG-capable browsers.
The quick way: img elementTo embed an SVG via an <img> element, you just need to reference it in the src attribute as you'd expect. You will need a height or a width attribute (or both if your SVG has no inherent aspect ratio). If you have not already done so, please read Images in HTML.
SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document.
SVG files are great for web graphics like logos, illustrations, and charts. But their lack of pixels makes displaying high-quality digital photos difficult. JPEG files are generally better for detailed photographs. Only modern browsers can support SVG images.
I can recommend the SVG Primer (published by the W3C), which covers this topic: http://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.
2014 update:
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, modernizr 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 on svg fallbacks.
From IE9 and above you can use SVG in a ordinary IMG tag..
https://caniuse.com/svg-img
<img src="/static/image.svg">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With