6

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.

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742

2 Answers2

8

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.

Community
  • 1
  • 1
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
0

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)
HIRA THAKUR
  • 17,189
  • 14
  • 56
  • 87
  • Thanks for your answer. Why do you think polling is needed? In my experimentation across Chrome/Firefox/IE when the `load` event fires, the SVG document is available. – Drew Noakes Oct 02 '13 at 15:40
  • Also, I don't need to add an `id` to the element as I already have a reference to it (`e` in my example.) – Drew Noakes Oct 02 '13 at 15:40
  • just a quick solution..yours is a better one.i will jst get rid of the polling part – HIRA THAKUR Oct 02 '13 at 15:42
  • Further, `clear_me_later` is private to the event callback function, so the call to `clearInterval` won't work. – Drew Noakes Oct 02 '13 at 15:42