SVG <使用xlink :href> from a CDN

标签 svg cdn xlink svg-sprite

我正在使用 <use xlink:href>引用我的svg文件。
它在我的本地运行良好,但当我从 CDN 引用它时会抛出错误 (CORS)。看起来好像 xlink:href不允许 CORS 请求,但我想知道是否有任何解决方案?

另一方面,我听说这种 Sprite 技术在 SVG2 上已被弃用。那么目前使用 sprite SVG 文件的最佳解决方案是什么,它适用于所有不同的浏览器,包括移动浏览器。

最佳答案

我发现的最简单的跨浏览器解决方案是通过 ajax 获取 SVG sprite 并将其嵌入到您的页面中:

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

这也使您无需在 xlink:href 中指定 SVG Sprite 的 URL

<svg>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#heart"></use>
</svg>

关于SVG <使用xlink :href> from a CDN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39617188/

相关文章:

html - 为什么我的 Logo div 中的 svg 将我的导航从我的标题中推出

android - svg 图像文件 Android

http - 对别名域的请求是否会被浏览器缓存?

joomla - 谷歌云平台: Temporary Server error?

javascript - 修改svg xlink :href through knockout attr binding

javascript - 将鼠标悬停在 svg map 上时突出显示表格

angular - 使用 svg 文件作为 Angular 应用程序的背景

cdn - Amazon Cloudfront 设置以减少等待时间

javascript - 在 JavaScript 中动态创建 SVG 链接

c# - ASP.net 在 XDocument 中创建 XLink 节点