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.
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.
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:
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.
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 )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With