简体   繁体   English

LabJS和document.body.appendChild

[英]LabJS and document.body.appendChild

I am using LabJS and in one of my js file have a document.body.appendChild(). 我正在使用LabJS,在我的一个js文件中有一个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. 它似乎工作正常,但我想知道它是否可能遭受与document.write相同的潜在异步问题,或者其行为是否不同。

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). 在执行document.body.appendChild()之前,您需要知道DOM已完成解析,因为在解析完成之前尝试以这种方式修改DOM可能会导致错误(实际上,在某些版本的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. 因此,如果您使用LabJS动态加载脚本,并且在解析文档之前进行了此操作,则可能会在文档完成解析之前造成脚本加载和运行的问题。

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. 防止脚本运行得太早的通常方法是要么直到</body>标记之前都不尝试加载它,要么使用某种DOM准备就绪的检测逻辑,以便在DOM准备就绪时通知您的脚本。仅在安全的情况下运行其逻辑。 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). 我不了解LabJS的详细信息,以了解它是否具有自己的DOM就绪检测逻辑(我初看起来没有这种功能)。

If you are using any other framework (jQuery, YUI, etc...), it probably has such logic. 如果您使用任何其他框架(jQuery,YUI等),则可能具有这种逻辑。 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. 如果不是,这里有一个普通的javascript docReady()函数: 纯JavaScript等效于jQuery的$ .ready()如何在页面/ dom准备就绪时调用该函数 ,您可以使用该函数来确保您的DOM修改代码不会太早运行。

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

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