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.
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>
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With