My goal is to save SVG icons as <symbol>
markup in localStorage and then inject them after the DOMContentLoaded
event.
Initially, I planned to utilize document.createElement('svg')
and insert the element before the first node in document.body
.
However, it seems that in Chrome (and possibly other browsers), the icon does not display unless I set the innerHTML of a div with the string representation of the <svg>
element, and then insert the div into the document.
Below is a simplified example:
var sprites = document.getElementById('sprites');
var circles = [
'<symbol id="circle-yellow"><circle cx="25" cy="25" r="20" fill="yellow" /></symbol>',
'<symbol id="circle-blue"><circle cx="25" cy="25" r="20" fill="blue" /></symbol>'
];
// Insert the yellow circle symbol by creating an SVG element.
var yellowDiv = document.createElement('div');
var yellow = document.createElement('svg');
yellow.innerHTML = circles[0];
yellowDiv.appendChild(yellow);
sprites.appendChild(yellowDiv);
// Insert the blue circle symbol by inserting the SVG string.
var blueDiv = document.createElement('div');
blueDiv.innerHTML = '<svg>' + circles[1] + '</svg>';
sprites.appendChild(blueDiv);
#sprites {
dispay: none;
}
svg {
border: 2px solid black;
}
<svg height="50" width="50"><use href="#circle-yellow"></use></svg>
<svg height="50" width="50"><use href="#circle-blue"></use></svg>
<!-- Will hold <svg> elements referred to by <use> elements. -->
<div id="sprites"></div>
Why is the yellow circle not visible?
I have a suspicion that it may be related to the <svg>
element for the yellow circle not displaying as a 150x300 box at the bottom of the page. This is puzzling because both <svg>
elements are children of a div with display: none
, so neither should be visible.