views:

46

answers:

2

I have a function that loads a SVG Dom from a file. Currently, it creates an embed element and places it in the document, then waits for it to load with an onload event. Apparently, however, onload isn't called for elements placed in the document after the page has loaded. Is there a way that I can register a function to be called after the element has finished loading?

This is what I have:

function loadSVG(svgFilename, callback)
{
  // Loads data from an svg file
  // loadSVG(
  //           svgFilename, // The path to the file to load
  //           callback     // The function to be called with the
  //                        // SVG document once it loads.
  //        );            
  var embed = document.createElement("embed");
  embed.src = svgFilename;
  embed.onload = function() // Doesn't get called because page has already loaded
  {
    var doc = embed.getSVGDocument();
    document.getElementById("SVGLoader").removeChild(embed);
    callback(doc);
  };
  document.getElementById("SVGLoader").appendChild(embed);
}
A: 

Relevant: http://stackoverflow.com/questions/337293/how-to-check-if-an-embedded-svg-document-is-loaded-in-an-html-page

If you have control over the SVG document, could you not add a script in it that calls a function in the browser window?

Or, as the answer to that question suggested, polling to see if the SVG document has finished loading.

CD Sanchez
Thanks, but I figured it out myself: http://stackoverflow.com/questions/3705218/waiting-for-element-load-after-page-has-loaded/3705364#3705364
Na7coldwater
A: 

I figured out the problem, I was loading the SVG document in a div tag that was hidden with style="display:none". For some reason, the browser didn't load the embed when it was in this tag. When I removed the style attribute, the onload event fired the way I expected it to.

Na7coldwater
I'd probably reorder the script such that the onload handler is defined before you set 'src', just in case the load happens immidiately. Also you should consider switching to `<object>` instead of `<embed>`.
Erik Dahlström
Thanks, Erik, I'll consider it.
Na7coldwater