Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 973
Drew Noakes Avatar asked Oct 02 '13 12:10

Drew Noakes


People also ask

Can the onload attribute be used on other elements?

However, it can be used on other elements as well (see "Supported HTML tags" below). The onload attribute can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.

Why can't I check if the contentDocument is loaded?

Checking the contentDocument won't work if the iframe src points to a different domain from where your code is running. Show activity on this post. in my case it was a cross-origin frame and wasn't loading sometimes. the solution that worked for me is: if it's loaded successfully then if you try this code:

How to watch for iframe or IMG elements loading?

A better approach is to use the onload DOM event. This event works on tags such as iframe and img. For other tags, this is the pseudo code you can take inspiration from: NOTE: The trick is to attach an iframe or img element after every element you want to watch for their loading.

What can I do after successfully loading HTML content?

But you can do whatever task you want after successfully loaded your HTML content or a particular HTML content. In the first place, create an HTML file where I am gonna have an iframe. My task is to print an alert message when the iframe gets fully loaded. ( You can use your own HTML element instead of iframe, you can use image or anything )


1 Answers

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.

like image 116
Drew Noakes Avatar answered Oct 13 '22 12:10

Drew Noakes