SVG: Run the script when the document is loaded

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

If I were to do this using HTML and jQuery, I would just use $(document).ready(...) . I want to do the same in an SVG document, but obviously I cannot use jQuery in the same way.

In general, 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 to do this in a script, and not depending on the explicit onload="init()" in the SVG definition. (I want to write a script that could potentially be included in multiple SVGs without having to have any knowledge of how the script works.)

+6
source share
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> 
+7
source

Perhaps "onload" is the event you are looking for. Look here

+2
source

Nothing (but IE) prevents you from using the standard DOM event handlers in JS built into SVG:

 document.addEventListener('load', init); 

For IE, attachEvent is usually used or so, but I do not know if IE (> = 9) supports this in SVG.

Basically, SVG files are autonomous, so DOMReady (aka DOMContentLoaded) and download events are not so far apart (compared to HTML, where dozens of CSS files and images need to be loaded). Thus, the difference from using a load event instead of a DOMReady event (which, unfortunately, has not yet been stabilized by standardization) will be negligible. Also, I never tried if browsers even fire the DOMReady event when the SVG DOM loads.

+2
source

You can try to include the script at the very end of the svg document, then you do not need to wait for the load event. But this may fail if you link to any external files in the ant document that they have not yet loaded when the script runs.

+2
source

Source: https://habr.com/ru/post/898706/


All Articles