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.
Use
srcset
Most current browsers today support the
srcset
attribute, which allows specifying different images to different users. For example, you can use it for 1x and 2x pixel density, and the browser will select the correct file.In this case, if you specify an SVG in the
srcset
and the browser doesn't support it, it'll fallback on thesrc
.This method has several benefits over other solutions:
srcset
should know how to handle it so that it only downloads the file it needs.If you need your SVGs to be fully styleable with CSS they have to be inline in the DOM. This can be achieved through SVG injection, which uses Javascript to replace a HTML element (usually an
<img>
element) with the contents of an SVG file after the page has loaded.Here is a minimal example using SVGInject:
After the image is loaded the
onload="SVGInject(this)
will trigger the injection and the<img>
element will be replaced by the contents of the file provided in thesrc
attribute. This works with all browsers that support SVG.Disclaimer: I am the co-author of SVGInject
The best option is to use SVG Images on different devices :)
This jQuery function captures all errors in svg images and replaces the file extension with an alternate extension
Please open the console to see the error loading image svg