我有代码迭代数组(由对象提供)并处理要在 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.body
为null
。您可以通过在 DOM 加载后执行代码来避免这种情况。
document.addEventListener("DOMContentLoaded", function() {
// The code
});
关于javascript - 出现间歇性 "Uncaught TypeError: Cannot read property ' appendChild' of null"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41389201/