SVG <use xlink:href> from a CDN

那年仲夏 提交于 2021-02-07 13:37:49

问题


I am using the <use xlink:href> to reference my svg file.
It works fine on my local but throws an error (CORS) when I reference it from a CDN. It looks as though the xlink:href doesn't allow the CORS request but I am wondering if there is any solution?

On the other hand, I have heard that this sprite technique is deprecated on SVG2. So what is the best solution to use sprite SVG file for now that works on all different browsers including mobile browsers.


回答1:


The simplest cross-browser solution I've found is to fetch the SVG sprite via ajax and embed it in your page:

<div id="svg-container" style="display: none"></div>
<script>
!function() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", '/path/to/cdn/sprite.svg');
    xhr.onload = function() {
        document.getElementById('svg-container').innerHTML = xhr.responseText;
    }
    xhr.send();
}();
</script>

This also saves you from specifying the SVG sprite's URL in xlink:href

<svg>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#heart"></use>
</svg>


来源:https://stackoverflow.com/questions/39617188/svg-use-xlinkhref-from-a-cdn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!