简体   繁体   English

怎么知道什么时候 <embed> 元素的内容已加载

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

I'm programmatically adding an <embed> tag to my HTML document: 我是以编程方式在我的HTML文档中添加<embed>标记:

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. 这工作正常,SVG元素按预期显示。 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. 但是,我想用JavaScript操作SVG元素,并且在将元素添加到DOM后立即尝试这样做失败,因为内容尚未加载。

How can I do this. 我怎样才能做到这一点。 Note that I want to do this without jQuery so please don't point to the jQuery API. 请注意,我想在没有jQuery的情况下这样做,所以请不要指向jQuery API。

As @RGraham points out in a comment, the <embed> element raises the load event when its content is ready. 正如@RGraham在评论中指出的那样, <embed>元素在其内容准备好时引发load事件。

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. SVG在加载之前立即被修改,然后进行绘制。

Assign an id to the created element. 为创建的元素分配id。

  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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM