I am using LabJS and in one of my js file have a document.body.appendChild(). It appears to work fine but I am wondering if it can suffer the same potential async issues that document.write does or if it behaves differently.
1 Answers
Before doing document.body.appendChild()
, you need to know that the DOM has finished parsing as attempting to modify the DOM in this way before it is done parsing can cause errors (you can actually cause a browser segfault in some versions of IE).
So, if you are using LabJS to load scripts dynamically and you are doing that before the document has been parsed, then you could create an issue of the script loading and running before the document was finished parsing.
The usual ways to prevent a script from running too early are to either not even attempt to load it until right before the </body>
tag or to use some sort of DOM ready detection logic so your script gets notified when the DOM is ready and runs its logic only when safe to do so. I don't know LabJS in detail to know if it has it's own DOM ready detection logic (I didn't see such a capability upon my first look).
If you are using any other framework (jQuery, YUI, etc...), it probably has such logic. If not, there is a plain javascript docReady()
function here: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it that you can use to make sure your DOM-modifying code doesn't run too early.