How to know when an <embed> element's content has loaded

10.9k Views Asked by At

I'm programmatically adding an <embed> tag to my HTML document:

var e = document.createElement('embed');
e.src = "some-image.svg";
e.type = "image/svg+xml";
document.body.appendChild(e);

This works fine, and the SVG element displays as expected. However, I want to manipulate the SVG elements with JavaScript, and attempting to do so immediately after adding the element to the DOM fails, as the content hasn't loaded yet.

How can I do this. Note that I want to do this without jQuery so please don't point to the jQuery API.

2

There are 2 best solutions below

1
On BEST ANSWER

As @RGraham points out in a comment, the <embed> element raises the load event when its content is ready.

So my code becomes:

var e = document.createElement('embed');
e.src = "img/z-slider.svg";
e.type = "image/svg+xml";
document.body.appendChild(e);

e.addEventListener('load', function()
{
    // Operate upon the SVG DOM here
    e.getSVGDocument().querySelector('#some-node').textContent = "New text!";
});

This is better than polling as there is no flicker. The SVG is modified immediately upon load, before it is painted.

4
On

Assign an id to the created element.

  function check_if_loaded() {
    var your_svg = document.getElementById("id").getSVGDocument();
    if (your_svg) {
        alert("loaded");

    } else {
        console.log("not yet loaded")
    }
}

your_element.addEventListener('load',check_if_loaded, false)