Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG: Run script when document has loaded

I have a SVG document, and I want to be able to include a script in it (using the <script> tag). Inside this script I want to set up a function that will be called when the document has loaded and is available for manipulation.

If I was doing this with HTML and JQuery I'd just use $(document).ready(...). I'm looking to do the same within an SVG document but obviously I can't use JQuery in the same way.

In summary, what I'm looking for is something like:

test.svg:

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
    <script type="text/ecmascript" xlink:href="myscript.js" />

    <!-- Rest of SVG body goes here -->
</svg>

myscript.js:

function init(evt) {
    var svgDocument = evt.target.ownerDocument;
    var svgRoot = svgDocument.documentElement;
    // Manipulate SVG DOM here
}

// --> Somehow attach init() function to onload event of SVG <--

I want to try and do this within the script rather than depending on an explicit onload="init()" in the SVG definition. (I want to write a script that could potentially be included in several SVGs without them needing to have any knowledge of how the script works.)

like image 302
FixMaker Avatar asked Oct 05 '11 21:10

FixMaker


4 Answers

Here is an example

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" onload='init(evt)'>
<script type="text/ecmascript">
function init(evt) {
var svgDocument = evt.target.ownerDocument;
var svgRoot = svgDocument.documentElement;
// Do whatever you like on svgRoot to manipulate your SVG DOM
}
</script>
</svg>
like image 144
Clafou Avatar answered Sep 18 '22 01:09

Clafou


Maybe 'onload' is the event, you are looking for. Look here

like image 29
madhead - StandWithUkraine Avatar answered Sep 18 '22 01:09

madhead - StandWithUkraine


Nothing (but IE) hinders you from using standard DOM event handlers in the JS embedded in SVG:

document.addEventListener('load', init);

For IE, you typically use attachEvent or so, but I don't know, if IE (>= 9) supports this in SVG.

Mostly, SVG files are standalone, so DOMReady (a.k.a. DOMContentLoaded) and load events are not this far apart (compared to HTML, where dozens of CSS files and images have to be loaded.) So the difference from using the load event instead of a DOMReady event (which is unfortunately not yet standardized stable) will be neglectable. Apart from that I've never tried, if browsers even fire a DOMReady event, when the SVG's DOM is loaded.

like image 23
Boldewyn Avatar answered Sep 21 '22 01:09

Boldewyn


You can try to include your script at the very end of the svg document, then you will not need to wait for the load event. But this may fail if you are referencing any external files in the document ant they have not already been loaded when the script is run.

like image 38
Spadar Shut Avatar answered Sep 20 '22 01:09

Spadar Shut