0

I want to access the DOM of an SVG file (let's call it /img/my_image.svg). I know two ways to achieve this:

1. Via the object tag

<object id="my_image" data="/img/my_image.svg" type="image/svg+xml" style="height: 100%">
    Image can't be displayed
</object>

JS code:

$('#my_image').on('load', function () {
    $(this.contentDocument).find('whatever').doWhatever();
}); 

2. Via an XMLSerializer

<div id="my_image"></div>

JS code:

$.get("/img/my_image.svg", function (data) {
    $('#my_image').html(new XMLSerializer().serializeToString(data.documentElement));
    $('#my_image').find('whatever').doWhatever();
});

Questions:

  1. Is one of these methods obviously better? Or is it a matter of preference?
  2. In which case should I prefer one or the other?
Métoule
  • 13,062
  • 2
  • 56
  • 84
  • It would be a matter of preference. 1st case you will avoid an ajax code which browser does it for you saving lines of code and unwanted complexity. 2nd case you can use if you want to lazy load an svg, saving memory and network by requesting on demand. – NiRUS Jun 02 '17 at 10:39

2 Answers2

1

After a bit of playing around, here are my findings :

1. Via the object tag

  • Hits the browser cache
  • Loads immediately
  • A new document is created for the SVG DOM

    • Styling the embedded SVG requires a different CSS file, cf How to apply a style to an embedded SVG?
    • All selectors must use that new document's context, for example :

      $('#my_id_in_svg', '#my_image').doWhatever();
      

2. Via an XMLSerializer

  • Hits the browser cache
  • Loading can be deferred (because it requires an AJAX call)
  • SVG DOM is inserted into the document's DOM
    • Styling can be done with the same CSS file
    • Selectors can use the document's context

Based on this, I think I'll use the second approach from now on.

Métoule
  • 13,062
  • 2
  • 56
  • 84
0

I've worked with SVG and used the object tag, but I've also used SVG via AJAX. But what can happen with the ajax request is that if the code is too large it can take up a considerable amount of time, and may even exceed the transfer limit (as has already happened to me), where the code arrives incomplete.

In general, it is only a matter of preference

GeekSilva
  • 481
  • 1
  • 5
  • 20