javascript - 出现间歇性 "Uncaught TypeError: Cannot read property ' appendChild' of null"错误?

标签 javascript html

我有代码迭代数组(由对象提供)并处理要在 iframe 中调用的图像源。问题是,我得到了一个

Uncaught TypeError: Cannot read property 'appendChild' of null

重新加载页面时出错。如果我执行清空缓存并硬重新加载,它似乎可以 100% 正常工作。如果我导航离开并返回,95% 的时间都可以正常工作。如果我定期重新加载,则以下代码中初始图像源 (document.body.appendChild(iframeTag); ) 的最后一行几乎每次都会发生错误。然而,我确实看到初始图像源调用出去了:

function insertStaticTag(imgSrc) {
    var iframeTag = document.createElement("iframe");
    iframeTag.setAttribute("width", "1");
    iframeTag.setAttribute("height", "1");
    iframeTag.style.display = "none";
    iframeTag.style.border = "none";
    var imgTag = document.createElement("img");
    imgTag.src = detokenizeTags(imgSrc);
    iframeTag.appendChild(imgTag);
    document.body.appendChild(iframeTag);
};

不确定为什么会发生这种情况或如何解决?有任何想法吗?

最佳答案

这意味着document.bodynull。您可以通过在 DOM 加载后执行代码来避免这种情况。

document.addEventListener("DOMContentLoaded", function() {
     // The code
});

关于javascript - 出现间歇性 "Uncaught TypeError: Cannot read property ' appendChild' of null"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41389201/

相关文章:

javascript - 使用javascript添加之前和之后

javascript - 使用 AJAX 填充后无法设置正确的 div 宽度

javascript - 如何打开要在其中运行 javascript 的 Ghost 本地 html 文件?

javascript - 如何在 CSS 中为浏览按钮指定样式(图像)?

javascript - 如何将 html 放入 javascript 变量中

html - 为什么在我使用边距时 IE 会创建一个空白区域?

javascript - jquery验证器错误位置

html - 哪个是处理 RTL CSS 的最佳方式

javascript - 在 map 实例上使用 map /过滤器行为

html - Bootstrap 输入组 1px 差异