2013-10-14 52 views
0

阻止頁面的其餘部分我有一個簡單的頁面:爲什麼不動態添加腳本加載

<!DOCTYPE html> 
<html> 
<head> 
    <script> 
    func = function(message) { 
     alert(message); 
    } 
    </script> 
</head> 
<body> 
    <h1> Visible content </h1> 
</body> 
</html> 

和腳本是在單獨的文件 - 比方說 - test.js

func("It should block the page."); 

當我簡單地添加這個腳本通過鍵入頭:

<script src="test.js"></script> 

警報內容之前顯示是可見的這對我來說很好。
然而,當我動態添加腳本:

<script> 
    var script = document.createElement('script'); 
    script.setAttribute('type', 'text/javascript'); 
    script.setAttribute('src', 'test.js'); 
    document.getElementsByTagName('head')[0].appendChild(script); 
</script> 

警報顯示內容之後。

這是爲什麼發生?瀏覽器是否應該等待直到腳本結束(包括添加和加載新腳本)?是否可以通過動態添加的腳本來阻止正文內容?

+0

您的DOM(文檔對象模型)是沒有準備好。您的代碼在呈現頁面上的元素之前執行。 你必須使用dom ready事件,例如在jquery中我們使用'$(document).ready(.. code ..);' – Dvir

回答

1

這是因爲異步加載的。看看文章:http://css-tricks.com/thinking-async/

這取決於你是什麼意思阻止。您可以加載隱藏內容塊的頁面:<div style="display:none;"></div>,並在頁面加載後顯示它。

這裏是jQuery的方式:

$(function() { 
    // do stuff after DOM has loaded 
}); 

看一看這個答案更多:javascript domready?

+0

我已經想出了這樣的解決方案,希望有其他的方法。無論如何感謝解釋異步加載;) – PGJ

-1

把它包裝的document.ready:

$(document).ready(function() { 
    var script = document.createElement('script'); 
    script.setAttribute('type', 'text/javascript'); 
    script.setAttribute('src', 'test.js'); 
    document.getElementsByTagName('head')[0].appendChild(script); 
}); 
+0

它不回答這個問題! – epascarello