Here's a summary of all the ways I could find for inserting SVGs into HTML templates together with their differences and their main pros and cons:
((( 1 )))
/* in CSS */
background-image: url(happy.svg);
This way neither allows JS interaction, nor the CSS itself
could have more fine-grained control on the svg parts.
((( 2 )))
<img src="happy.svg" />
Just like ((( 1 ))), neither allows JS interaction, nor the CSS itself could have more fine-grained control on the svg parts.
Methods ((( 1 ))) and ((( 2 ))) are only fine if you want a static svg.
Note: When using the <img>
tag, if you specify a SVG in the srcset
attribute and the browser doesn't support it, it'll fallback to the src
attribute automatically.
<img src="logo.png" srcset="logo.svg" alt="my logo">
((( 3 )))
<div>
<!-- Paste the SVG code directly here. -->
<svg>...</svg>
<!-- AKA an inline svg -->
<!-- would be the same if is created and appended using JavaScript. -->
</div>
This method does not have any of the caveats mentioned in ((( 1 ))) and ((( 2 ))), however, this method makes template code messy, and also SVGs are copy pasted, so they will not be in their own individual files.
((( 4 )))
<object data="happy.svg" width="300" height="300"></object>
OR:
<object data="your.svg" type="image/svg+xml">
<img src="yourfallback.jpg" />
</object>
Using this method the SVG will not be accessible using external CSS, but will be accessible using JavaScript.
((( 5 )))
Use iconfu/svg-inject to keep the SVGs in their own individual files (to keep the template code much cleaner), now add the SVGs using <img>
tags, and svg-inject will automatically turn them into inline SVGs, so they will be accessible to both CSS and JavaScript.
Note1: This method works also if img
s are added dynamically (using javascript).
Note2: SVGs added using this method are also cached by browsers just like images.
((( 6 )))
Using a single SVG sprite file, then use <use>
tags to insert them. This way is quite flexible too, having the same effect as ((( 5 ))). This method (and a few more) are shown in action in this video.
((( 7 )))
(React-specific way) Turn them into React components (or write a component that loads them).
((( 8 )))
<embed src="happy.svg" />
According to MDN, most modern browsers have deprecated and removed support for browser plug-ins. This means that relying upon <embed>
is generally not wise if you want your site to be operable on the average user's browser.
<svg>
from which you want to reference other SVGs. This can be achieved, e.g. using<image>
. – Ecru<load-file>
Web Component I blogged about. – Centuple