How to check if an embedded SVG document is loaded in an html page?

Viewed 45449

I need to edit (using javascript) an SVG document embedded in an html page.

When the SVG is loaded, I can access the dom of the SVG and its elements. But I am not able to know if the SVG dom is ready or not, so I cant' perform default actions on the SVG when the html page is loaded.

To access the SVG dom, I use this code:

var svg = document.getElementById("chart").getSVGDocument();

where "chart" is the id of the embed element.

If I try to access the SVG when the html document is ready, in this way:

jQuery(document).ready( function() {
var svg = document.getElementById("chart").getSVGDocument();
...

svg is always null. I just need to know when it is not null, so I can start manipulate it. Do you know if there is a way to do it?

8 Answers

For future reference: an Angular(8)/Typescript solution looks like this:

  @ViewChild('startimage', {static:false})
  private startimage: ElementRef;
...
  this.startimage.nativeElement.addEventListener('load', () => {
    alert('loaded');
  });

You can get to the svg by const svg = this.startimage.nativeElement.getSVGDocument();

You can assign an onload event handler to an element within your SVG document and have it call a javascript function in the html page. onload maps to SVGLoad.

http://www.w3.org/TR/SVG11/interact.html#LoadEvent

The event is triggered at the point at which the user agent has fully parsed the element and its descendants and is ready to act appropriately upon that element

You could try polling every so often.

function checkReady() {
    var svg = document.getElementById("chart").getSVGDocument();
    if (svg == null) {
        setTimeout("checkReady()", 300);
    } else {
        ...
    }
}
Related