Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG <use xlink:href> from a CDN

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.

like image 261
Omar Zeidan Avatar asked Sep 21 '16 12:09

Omar Zeidan


People also ask

How do I use XLink HREF in SVG?

If you need to support earlier browser versions, the deprecated xlink:href attribute can be used as a fallback in addition to the href attribute, e.g. <use href="some-id" xlink:href="some-id" x="5" y="5" /> . You can use this attribute with the following SVG elements: <a> <altGlyph>

How do I embed a link in SVG?

SVG shapes The simplest way to make a portion of an SVG clickable is to add an SVG hyperlink element to the markup. This is as easy as wrapping the target with an <a> tag, just as you would a nested html element. Your <a> tag can surround a simple shape or more complex paths.

Can svgs have links?

It is very similar to HTML's <a> element. SVG's <a> element is a container, which means you can create a link around text (like in HTML) but also around any shape.

How do I link SVG to HTML?

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document.


1 Answers

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>
like image 121
Micah Engle-Eshleman Avatar answered Sep 18 '22 06:09

Micah Engle-Eshleman