Skip to content

Instantly share code, notes, and snippets.

@MartinBspheroid
Last active October 1, 2020 14:42
Show Gist options
  • Save MartinBspheroid/5980be3297eb581ab172c82aac4a5ce3 to your computer and use it in GitHub Desktop.
Save MartinBspheroid/5980be3297eb581ab172c82aac4a5ce3 to your computer and use it in GitHub Desktop.
Replace
/////////// example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
svg {
stroke: white;
fill: red;
}
body {
background-color: black;
color: aliceblue;
}
.boo {
stroke: gainsboro;
fill: blueviolet;
}
</style>
</head>
<body>
<div class="hoo">Here be SVG</div>
<usvg class="boo" id="foo" width="90px" height="90px" src='close.svg'></usvg>
<usvg class="doo" id="woo" width="90px" height="90px" src='contrast.svg'></usvg>
<script src="./script.js"></script>
</body>
</html>
document.addEventListener("DOMContentLoaded", async () => {
let items = document.querySelectorAll("usvg");
items.forEach(async e => {
await insertSVG(e);
});
});
function insertSVG(source) {
fetch(source.getAttribute("src"))
.then(response => response.text())
.then(svg => {
function cloneAttributes(target, source) { // https://stackoverflow.com/a/50695433
[...source.attributes].forEach(attr => {
target.setAttribute(attr.nodeName, attr.nodeValue);
});
}
let svgClean = svg.replace(/\<\?xml.+\?\>/g, ""); /// remove prologue if there's any
svgClean = svgClean.replace(/\r?\n|\r/g, ""); /// slam whole file in one-liner (apparently parser is not happy about it)
let placeholder = document.createElement("div"); /// create placeholder
placeholder.insertAdjacentHTML("afterbegin", svgClean); ///append SVG element into placeholder
let parent = source.parentNode; // get parent node
let svgElement = placeholder.childNodes[0]; // get handle to SVG element
cloneAttributes(svgElement, source); // speak for it self, right?
parent.replaceChild(svgElement, source); // replace original placeholder by new SVG element
})
.then(svg => console.log("Done"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment