簡體   English   中英

在整個DOM准備就緒之前執行JS

[英]Executing JS before whole DOM is ready

好的,我就此發表了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>

^^這樣的東西存在嗎?

我不確定您要問的是什么,但是確保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>

因為您的代碼位於所有其他元素之后,所以當您的代碼最終加載並運行時,它們將存在以便進行操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM