前一段时间,我们开始将SVG包含为背景图像CSS。当时,由于IE的兼容性问题,我们发现仅将SVG用作
data:image/svg+xml;charset=UTF-8,<svg ...> ... </svg>
所以我们必须将它们设置为base64
data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL...
现在我们已经放弃了对IE <11的支持,还是需要这样做,还是可以像第一个示例中那样在数据URI中开始简单地使用SVG?
答案 0 :(得分:0)
要继续通过评论进行讨论,
对 URL编码 SVG字符串的一种既易读又比base64短的折衷方案,但是有一些技巧可以避免不必要的编码。这是一篇博客文章,介绍了此技术:
https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
..和执行此工作的工具:
https://codepen.io/jakob-e/pen/doMoML
https://github.com/tigt/mini-svg-data-uri
function specialHexEncode(match) {
switch (match) { // Browsers tolerate these characters, and they're frequent
case '%20': return ' ';
case '%3D': return '=';
case '%3A': return ':';
case '%2F': return '/';
default: return match.toLowerCase(); // Compresses better
}
}
var result = svg
.replace(/\s+/g, ' ') // Collapse whitespace
.replace(/"/g, "'"); // Swap quotes
result = encodeURIComponent(result) // Encode everything..
.replace(/%[\dA-F]{2}/g, specialHexEncode) // ..except a few special characters
return 'data:image/svg+xml,' + result;