Is it possible to get an XML SVG image using JavaScript?

My goal is to load an SVG image in JavaScript and have it both the image and the underlying SVG XML.

I can upload an image for example ...

var myImage = new Image();
myImage.src = "cat.svg";

      

Now that I have an image, how can I access the underlying XML that makes up the SVG image?

The only solution I came across was to load it again via ajax:

$(myImage).one("load", function(){
    $.ajax({
        url :       "cat.svg",
        cache :     true, 
        dataType :  "xml"
    }).fail(function( jqXHR, textStatus, errorThrown ) {
        console.error("Ajax failure loading image.");
    }).done(function( data, textStatus, jqXHR ){
        console.log("Got the image SVG XML:", $(data).find('svg'));
    });
});

      

But I feel like there might be a better way to do this.

+3


source to share


3 answers


Unable to extract image source from object Image

.

The AJAX solution included in your question is the only way to get the source.



If you only want to load the image once, perhaps you can first fetch it with AJAX and then use the extracted XML to render the image (for example, add to document as inline SVG or set source to data:

or Blob url
).

+5


source


As I know the svg will be improvised as soon as it loads. So I would suggest your path is quite possible.



All libraries I know (snap.svg, svg.js, etc.) only work with interpreted svg code. Even if it improves performance by several degrees, they rely on manipulating interpreted code ... so I would guess there is no way to get the source code from the interpreted svg.

+1


source


Use jQuery, test on chrome and firefox

$('#svgBase').html( '<circle cx="20" cy="20" r="10" stroke="black" stroke-width="2" fill="red"></circle> <circle cx="50" cy="20" r="10" stroke="black" stroke-width="2" fill="green"></circle>')
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<svg id="svgBase"></svg>
      

Run codeHide result


+1


source







All Articles