SVG <use xlink:href> from a CDN
Asked Answered
C

1

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.

Cropland answered 21/9, 2016 at 12:55 Comment(1)
@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.Casillas
T
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>
Tenpins answered 24/1, 2019 at 7:49 Comment(1)
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 lotCropland

© 2022 - 2024 — McMap. All rights reserved.