问题
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