8

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.

BuZZ-dEE
  • 6,075
  • 12
  • 66
  • 96
Omar Zeidan
  • 133
  • 7
  • @Chenmunka Please don't suggest edits to remove tags. This takes at least three people to review, whereas people with >2k rep can do these edits singlehandedly. We appreciate your willingness to cooperate, but this is unfortunately not the right way. – Luuklag Sep 21 '18 at 11:13

1 Answers1

5

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>
  • I am not sure that this will get cached, as this technique can also be valid by using `xlink:href="path/to/file#heart`. Thanks for your help! I can't believe that I asked this 3 years ago :)) I am not sure if this is still valid tho! Thanks a lot – Omar Zeidan Feb 10 '20 at 19:50