将引入的 SVG 转换为代码形式
在网页中引入 SVG 文件时,查看源代码可能只看到一个类似 ./test.svg 的文件路径,而其他网站引入的 SVG 却是大段的编码。本文将介绍如何通过代码的形式引入 SVG 文件。
为此,可以使用以下步骤:
以下代码示例演示了如何实现此过程:
<div id="test"></div>
fetch('https://static.segmentfault.com/main_site_next/614d2165/_next/static/media/sf-icon-small.4d244289.svg') .then(body => body.text()) .then(svg => (new DOMParser).parseFromString(svg, 'image/svg+xml')) .then(actualSVG => { // append to the body or do your thing document.querySelector('#test').appendChild(actualSVG.documentElement) });