0

I have a function that modifies the contents of an SVG based on some values I calculate from the SVG file. Namely, it calculates the length of each path in the file. As such, the SVG file must be completely loaded before running the script to calculate this.

I have the script inside $("#logoSVG").load(function(), but this is never run, for some reason. I have also tried $(window).load(function(), and this runs, but before the SVG is loaded (because the amount of paths in the document still returns 0 at this point). Here is the full script:

<script>
    $("#logoSVG").load(function(){

    var path = document.getElementsByTagName('path');
    var length;
    var anim = document.getElementsByTagName('animate');

    for(i = 0; i < path.length; i++){
        length = path[i].getTotalLength().toString();
        path[i].setAttribute('stroke-dasharray',length+','+length);
        anim[i].setAttribute('values','-'+length+';0');
    }

    });
</script>

I know the script works because I've tested it in another document in which the SVG is written inline. In this case, I am loading it into an <object>:

<object id="logoSVG" data="imgs/logo.svg" type="image/svg+xml" style="display:block;">
      <img src="imgs/fallback.png" width="100%" style="display:block;"/>
</object>

How can I get the script to not run until after the SVG is loaded?

NOTE: It's possible I may be completely wrong on this, and it actually is being called after loading. If that's the case however, for some reason none of the <path> elements are being detected. Why would this be? Is there something else I have to do to access these elements once they have been inserted into the page?

GtwoK
  • 497
  • 4
  • 16

2 Answers2

0

Did not realize there was a certain way to handle svg files loaded into an <object>. See here.

Community
  • 1
  • 1
GtwoK
  • 497
  • 4
  • 16
0

You're not using the correct document object for getElementsByTagName(), so you won't get the matches you expect. It works fine in the inline case because then there's only one document. When you use <object> you create a separate document with the referenced content. If you want to access the referenced document from a script in the top-level document just make sure to get the proper document object.

By using the contentDocument attribute on the embedding element (e.g object or iframe) you can get the right document object for the content.

Erik Dahlström
  • 59,452
  • 12
  • 120
  • 139