This is a self Q&A of a handy piece of code I came up with.
Currently, there isn\'t an easy way to embed an SVG image and then have access to the SVG elements vi
There is an open source library called SVGInject that uses the onload
attribute to trigger the injection. You can find the GitHub project at https://github.com/iconfu/svg-inject
Here is a minimal example using SVGInject:
After the image is loaded the onload="SVGInject(this)
will trigger the injection and the element will be replaced by the contents of the SVG file provided in the
src
attribute.
It solves several issues with SVG injection:
SVGs can be hidden until injection has finished. This is important if a style is already applied during load time, which would otherwise cause a brief "unstyled content flash".
The elements inject themselved automatically. If you add SVGs dynamically, you don't have to worry about calling the injection function again.
A random string is added to each ID in the SVG to avoid having the same ID multiple times in the document if an SVG is injected more than once.
SVGInject is plain Javascript and works with all browsers that support SVG.
Disclaimer: I am the co-author of SVGInject