Loading SVG into SVGWeb dynamically with JQuery -
i trying dynamically display svg content. content stored string in data source. example string following:
<svg width="200" height="200" style="background-color:#d2b48c; margin-bottom:5px;" id="embeddedsvg"> <g id="mygroup" fill="blue" style="font-size:18px; text-anchor:middle; font-family: serif;"> <circle id="mycircle" cx="100" cy="75" r="50" stroke="firebrick" stroke-width="3" /> <text x="100" y="155">hello world</text><text x="100" y="175">from embedded svg!</text> </g></svg>
to accomodate ie, i'm using svgweb. problem is, display svg content, need wrap in <script type="image/svg+xml"></script>
tag combo. challenge is, svg being pulled asynchronously via jquery. and, knowledge, can't dynamically write 'script' tag javascript.
how take svg content retrieved jquery , dynamically display it?
found partial answer here , reproduced below. note, approach forces build root <svg>
tags , attributes in javascript instead of loading whole svg document have in question's example.
dynamically creating svg root element similar direct embedding web page. don't have create script tag if direct embedding svg on page load:
<script type="image/svg+xml"> <svg> ... </svg> </script>
instead, follow process similar above:
// create svg root element var svg = document.createelementns(svgns, 'svg'); // don't need pass in 'true' svg.setattribute('width', '300'); svg.setattribute('height', '300'); // create example circle , append svg root element var circle = document.createelementns(svgns, 'circle'); svg.appendchild(circle);
must use callback know when svg appended page (this slight divergence standard). following supported ways this:
svg.addeventlistener('svgload', function() { svg = this; // correctly refer svg root alert('loaded!'); }, false); // supported: svg.onsvgload = function() { alert('loaded!'); }
now append svg root our document
svgweb.appendchild(svg, document.body); // note call svgweb.appendchild
note in above code have use event listener know when svg root finished loading page; slight divergence standard necessary svg web's magic.
the parent attach either svg root must attached real dom on page (i.e. can't disconnected page).
Comments
Post a Comment