1

I have code that iterates through an array (which is fed by an object) and processes image sources to be invoked in an iframe. The issue is, I'm getting an

Uncaught TypeError: Cannot read property 'appendChild' of null

ERROR when reloading page. If I do a Empty Cache and Hard reload it seems to works fine 100%. If I navigate away and back it works fine 95% of the time. If I do a regular reload, the error occurs almost every time on the last line, of the initial image source (document.body.appendChild(iframeTag); ) in the following code. I do however see the initial image source call going out :

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);
};

Not sure why this is happening or how to fix? Any ideas?

anon
  • 855
  • 12
  • 22
Michael Johns
  • 419
  • 3
  • 21

1 Answers1

1

It means document.body is null. You can avoid it by executing the code after the DOM is loaded.

document.addEventListener("DOMContentLoaded", function() {
     // The code
});
  • This worked: `if(window.addEventListener) window.addEventListener("load", function() { document.body.appendChild(iframeTag); }, false); else window.attachEvent("onload", function() { document.body.appendChild(iframeTag); }); };` – Michael Johns Dec 30 '16 at 06:22