0

好的,我对此发表了 2 篇文章,但不知何故,我无法将其融入我的脑海中。

所以我得出结论,如果我们有这样的事情:

<script type="text/javascript" src="somefile.js"></script>
<script type="text/javascript">
func1();
</script>

并且 func1() 是在 somefile.js 中定义的,它保证在浏览器到达该 inline 时运行。

但是,如果我有一个大页面(不考虑图像等,只是 html)需要几秒钟来加载并且 DOM 准备就绪(据我所知,当整个 html 代码已加载并且已解析)并且我想要执行一些代码并处理已加载的页面部分,而大页面的其余部分仍在加载?

例如:

<div id="div1">Some div where content will be inserted by the inline javascript below</div>
<script type="text/javascript"> notifyPartLoaded("div1"); </script>

^^这样的东西存在吗?

4

1 回答 1

1

我不确定您的问题是什么,但确保 DOM 准备就绪的一种简单方法是将您的 JavaScript 放在 HTML 的底部,就在结束</body>标记的旁边。

<!doctype html>
<html>
    <head>
        <title>some title</title>
        <!-- this script could go toward the bottom too, but it must be before --> 
        <!--   your script if your script relies on it -->
        <script type="text/javascript" src="somefile.js"></script>
    </head>
    <body>  
        <div id="div1">Some div where content will be inserted by the inline javascript below</div>
        <!-- your HTML -->
        <!-- your HTML -->
        <!-- your HTML -->

        <!-- Place your script last -->
        <!-- ...though it would be better to have it in a separate file -->
        <script type="text/javascript"> notifyPartLoaded("div1"); </script>
    </body>
</html>

因为您的代码在所有其他元素之后,所以当您的代码最终加载和运行时,它们将存在以供操作。

于 2011-06-18T21:59:58.540 回答