Search code examples
javascripthtmlsvgexternal

Can you make a simple call to an external javascript file inside an SVG, onload?


I have a SVG image. I would like to program that SVG image to call an external javascript file when it loads. I have tried a few different strategies and none of them have worked. I feel the closest I have gotten is by putting creating an alert in an onload function in the <svg> tag.

<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
 width="474.000000pt" height="316.000000pt" viewBox="0 0 474.000000 316.000000"
 preserveAspectRatio="xMidYMid meet" onload="alert(2)">

The alert in the onload box works, but I'm not sure if you can call upon some external javascript code inside those quotes. Ideally, that is what I would do.

I have also tried adding a standard <script src="https://mycode.js"></script> tag right under the beginning <svg> tag but before the <g transform=..... and that doesn't work either. I can call an alert, and that will work, but not an external script. The shortest/simplest solution is pretty important in this scenario too.

Any help is greatly appreciated.

EDIT: I was able to solve my first problem, which was that I couldn't get any request sent out in the first place. I am able to send a request out now onload.
<svg onload="const xhr = new XMLHttpRequest();xhr.open('GET', 'https://external.js');xhr.send(null);">
So now it's 'GET'ing the external JS file but not loading/triggering it on the other end (because it's not requesting it as a script source). Any way to use this base to request it as a script source?

SOLVED:

The working code is:

<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
 width="474.000000pt" height="316.000000pt" viewBox="0 0 474.000000 316.000000"
 preserveAspectRatio="xMidYMid meet" onload="function loadScript( url ) {let script = document.createElement('script') 
script.type = 'text/javascript'; script.src = url; document.head.appendChild(script); 
} loadScript('https://external.js')">

Solution

  • This is what I would try:

    function loadScript( url ) {
      let script = document.createElement( "script" )
          script.type = "text/javascript";
          script.src = url;
         document.head.appendChild(script); 
    }
    
    //Set the event listener, in this case vue:
    
    <svg onload="loadScript('https://mycode.js')" />
    

    If you are not using vue or react or something similar you need to add the onload function with a querySelector or something.