在整个 DOM 准备好之前执行 JS
好吧,我发了两篇关于这个的帖子,但不知怎的,我无法把它纳入我的小头脑中。
所以我得出的结论是,如果我们有这样的东西:
<script type="text/javascript" src="somefile.js"></script>
<script type="text/javascript">
func1();
</script>
并且 func1() 在 somefile.js 中定义,那么当浏览器到达该 inline 时,保证它会运行。
但是,如果我有一个大页面(不考虑图像等,只考虑 html),需要几秒钟的时间来加载并且 DOM 准备好(据我所知,当整个 html 代码加载完毕后,DOM 就准备好了,并且解析)并且我想要执行一些代码并在已加载的页面部分上工作,而大页面的其余部分仍在加载?
例如:
<div id="div1">Some div where content will be inserted by the inline javascript below</div>
<script type="text/javascript"> notifyPartLoaded("div1"); </script>
^^ 这样的东西存在吗?
Ok, I made 2 posts about this but somehow I can't get it into my little mind.
So I concluded that if we have something like this:
<script type="text/javascript" src="somefile.js"></script>
<script type="text/javascript">
func1();
</script>
and func1() is defined in somefile.js, it is guaranteed to run when browser reaches that inline .
However, what if I have a big page (not taking into account images etc, just html) that takes a few seconds to load and for DOM to become ready (as I understand the DOM becomes ready when the whole html code has been loaded and parsed) and I want some code to be executed and work on parts of the page that have been loaded while the rest of the big page is still loading?
For example something like:
<div id="div1">Some div where content will be inserted by the inline javascript below</div>
<script type="text/javascript"> notifyPartLoaded("div1"); </script>
^^ Does something like this exist?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定你的问题是什么,但确保 DOM 准备就绪的一个简单方法是将 JavaScript 放置在 HTML 的底部,就在结束
标记内。
因为您的代码位于所有其他元素之后,所以当您的代码最终加载和运行时,它们将存在以供操作。
I'm not certain what your question is, but a simple way to ensure DOM ready is to place your JavaScript at the bottom of the HTML, just in side the closing
</body>
tag.Because your code is after all the other elements, they will exist for manipulation when your code finally loads and runs.