Element after injection (SVG loaded from image.svg):
`html
`
Why should I use it?
An SVG can only be properly styled with CSS and accessed with Javascript on element level if the SVG is inline in the DOM. With SVGInject you can keep your SVGs as individual files, but still access them with CSS and Javascript.
How to install SVGInject?
$3
Include the SVGInject Javascript file in the
element of the HTML document, or anywhere before the first usage of SVGInject`html
onload="SVGInject(this)" to any element where you want the SVG to be injected.
For most use cases this approach is recommended and provides nice advantages.
`html
`
$3
`html
`
Hooray :tada: - The SVGs get injected and are styleable!!!
What are the advantages?
* Wide browser support: Works on all browsers supporting SVG. Yes, this includes Internet Explorer 9 and higher! (full list)
* Fallback without Javascript: If Javascript is not available the SVG will still show. It's just not styleable with CSS.
* Fallback if image source is not available: Behaves like a normal
element if file not found or not available.
* Prevention of ID conflicts: IDs in the SVG are made unique before injection to prevent ID conflicts in the DOM.
What are additional advantages when using
onload?
The recommended way to trigger injection is to call
SVGInject(this) inside the onload attribute:`html `
This provides additional advantages:
* Intuitive usage: Insert SVG images into HTML code just as PNG images, with only one additional instruction. It's very clear to understand what it does by looking at the pure HTML.
* Works with dynamic content: If
elements are added dynamically, injection still works.
* Built-in prevention of unstyled image flash: SVGInject hides
elements until injection is complete, thus preventing a brief flicker of the unstyled image (called unstyled image flash).
* Early injection: The injection can already start before the DOM content is fully loaded.
* Standard-conform: The
onload event handler on elements has long been supported by all browsers and is officially part of the W3C specification since HTML5.0.
If you do not want to use the
onload attribute but prefer to inject SVGs directly from Javascript, you can find more information here.
What are the limitations?
SVGInject is intended to work in production environments however it has a few limitations you should be aware of:
* The image source must conform to the same-origin policy, which basically means the image origin must be where the website is running. This may be bypassed using the Cross-Origin Resource Sharing (CORS) mechanism. * Due to the same-origin policy SVGInject does not work when run from the local file system in many browsers (Chrome, Safari), yet in Firefox it works.