Snap.load() callback function triggered too late in Safari

208 views Asked by At

PROBLEM

In my code MySymbolsObject.js - code reported inline just for example purposes - set a window.onload event in order to Snap.load() a svg file and save the svg fragment node in Symbols.resources

The last inline <script> set a second window.onload event containing code that uses the svg node saved in Symbols.resources

In Firefox it works flawless printing the node in the console, in Safari Symbols.resources is printed as its original 0 value in the console.

I CHECKED

  • in the Safari console, after the page fully loads Symbols.resources contains the node.

  • the expected execution order of the two onload events is respected in both the browsers.

My guess is that Snap.load() runs asynchronously so It has unpredictable behavior in different browsers.

How can resolve in Safari?

<html>
<head>

  <script type="text/javascript" src="snap.svg-min.js"></script>


  <script type="text/javascript" src="MySymbolsObject.js">

      setEvent( window, 'load', function(){ 
          Snap.load( 'pathToFile.svg', function( svgFrag ){ 
               Symbols.resources = svgFrag;
          });
      });

      Symbols = { 
          resources : 0,
          ...
      }

  </script>


  <script type="text/javascript">

      onload = function (){
          console.log( Symbols.resources )
      }

  </script>

</head>

<body> ... </body>

</html>
1

There are 1 answers

0
Peter Romolo On BEST ANSWER

I found a way to postpone the execution of the window.onload code until Symbols.resources is ready.

The actual code is moved in the function main(), window.onload just checks repeatedly for Symbols.resources to be ready and finally call main().

onload = function (){
    if( Symbols.resources ) main();
    else setTimeout( window.onload, 10000 );
}

function main(){
    console.log( Symbols.resources );
}