Preloading SVGs in javascript

I am aware that javascript can make use of the Image() object to prime images before output, however I need the same functionality for SVGs. I don't want to be loading it into an "img" tag but rather building the SVG markup in javascript and ensuring the src files are loaded before I dump them to the screen. Does any one know if this is possible and how to achieve it?

Thanks.

Answers:

Answer

Just retrieve your SVG files via a usual AJAX-GET request and insert the code upon success of this request.

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

you can use 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);
Answer

You could create an <iframe>, add an event listener for 'load' on the iframe and then set the src of the iframe to the svg you want to load.

E.g:

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

If you want you can import the elements into the main document, just note that you need to either import or adopt the nodes into the main document before trying to append them.

It's probably more natural to just use XmlHttpRequest like Sirko suggested.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.