在javascript中预加载SVG

时间:2012-04-26 09:47:45

标签: javascript jquery image svg preloading

我知道javascript可以在输出之前使用Image()对象来填充图像,但是我需要SVG的相同功能。我不想将它加载到“img”标签中,而是在javascript中构建SVG标记并确保在将src文件转储到屏幕之前加载它们。有没有人知道这是否可能以及如何实现它?

感谢。

3 个答案:

答案 0 :(得分:3)

只需通过通常的AJAX-GET请求检索您的SVG文件,并在此请求成功时插入代码。

$.get( 'path/to/your/svg/file.svg', function(data) {
  $('#svgContainer').html( data );
});

答案 1 :(得分:1)

您可以使用createElementNS()

var img = document.createElementNS('http://www.w3.org/2000/svg','image');
img.setAttributeNS(null,'height','536');
img.setAttributeNS(null,'width','536');
img.setAttributeNS('http://www.w3.org/1999/xlink','href','https://upload.wikimedia.org/wikipedia/commons/2/22/SVG_Simple_Logo.svg');
img.setAttributeNS(null,'x','10');
img.setAttributeNS(null,'y','10');
img.setAttributeNS(null, 'visibility', 'visible');
$('svg').append(img);

答案 2 :(得分:1)

您可以创建一个< iframe>,在iframe上为'load'添加一个事件监听器,然后将iframe的src设置为您要加载的svg。

E.g:

var iframe = document.createElement("iframe");
iframe.addEventListener('load', function() {
  ... svg now loaded, do something ...
});
iframe.src = "your.svg";

如果您希望可以将元素导入主文档,只需注意在尝试附加主文档之前需要importadopt节点。

使用像Sirko建议的XmlHttpRequest可能更自然。

相关问题