Loading in SVG's from a file using JavaScript
I am not sure how to load in an SVG from a file using JavaScript.
I want to then reference the SVG in several places using a 'use' attribute.
Sometimes I just add the whole SVG using 'innerHTML'. I put this in a file and create a 'script' element with a 'src' of the file. I then add the 'script' element to the document 'body'.
Sometimes I need to use 'createElementNS' to create an 'svg' element, and then I can add the SVG's contents using 'innerHTML'.
Other times this does not work and maybe I need to create other elements of the SVG with 'createElementNS'.
Another way is to convert the SVG to a 'data URL' for a 'background-image' attribute within a CSS rule. I put this in a file, and create a 'link' element with an 'href' of the file and a 'rel' attribute set to "stylesheet". I then add the 'link' element to the document head. To convert the SVG to a 'data URL' I use the tool at:
yoksel.github.io/url-encoder/
I had to use the 'data URL' method when the SVG had an 'xlink:href' attribute pointing to a gradient in a 'defs' tag.
Maybe it would be simpler just to have several 'img' elements with their 'src' pointing to the SVG's. The browser would cache the images. However, I like to delay the loading of the SVG's until well after the page loads so the page loads quickly. I could create 'img' element in JavaScript but the images would still be loaded individually whereas I can put all the 'data URL' in one CSS file.
In the end, I now put SVG's into 'data URL's whenever I can.

Comments
Post a Comment