我在一段时间后找到(并自定义)一个片段,允许将SVG文件的<img>
标记转换为实际的<svg>
元素。这一直很有效,但我认为它可以更加优化。
jQuery('img.svg').each(function(){
var oThis = jQuery(this); //Store it so it can be easily referenced inside of the AJAX function
if ( oThis.attr('src').indexOf('.svg') >= 1 ){ //If it is actually an SVG image
jQuery.get(oThis.attr('src'), function(data){ //AJAX begins...
var theSVG = jQuery(data).find('svg'); //Get the SVG tag, ignore the rest
theSVG = theSVG.attr('id', oThis.attr('id')); //Add replaced image's ID to the new SVG
theSVG = theSVG.attr('class', oThis.attr('class') + ' replaced-svg'); //Add replaced image's classes to the new SVG
theSVG = theSVG.attr('data-original-src', oThis.attr('src')); //Add an attribute of the original SVG location
theSVG = theSVG.removeAttr('xmlns:a'); //Remove invalid XML tags
oThis.replaceWith(theSVG); //Replace image with new SVG
}, 'xml');
}
});
基本上,正在做的只是获取src
标记的<img>
和AJAXing来检索文件本身,然后用实际的<svg>
代码替换该元素。
当发生这种情况时,页面加载会有一个FOUC(因为有时我会使用CSS对SVG进行样式化,因此在AJAX仍在进行时,它会首先显示未加样式的<img>
标记。
为了解决这个问题,并且为了减少一般的请求,我想我会尝试对此进行优化。
有没有办法拉动浏览器已经在页面加载时请求的SVG文件,而不是使用AJAX来请求完全相同的文件?