簡體   English   中英

加載所有JS文件時的瀏覽器事件

[英]Browser event when all JS files loaded

我的AJAX應用基本上是一個index.html加上一堆.js模塊。 我的設置函數將js處理程序代碼連接到適當的DOM元素。 我懷疑我需要使用window.onload()而不是jquery的$(document).ready(),因為所有.js文件都需要在連接時可用(即下載)。

我的理解是$(document).ready()僅准備好DOM樹,但不能保證.js文件已加載。 那是對的嗎?

PS。 我不需要多個onload處理程序; 一個window.onload()對我來說很好。

在這種情況下,您肯定會有誤解。 之所以認為最好在body標簽關閉之前包含您的腳本標簽的全部原因是因為腳本加載正在阻止加載。 除非另行特別編碼(即Google Analytics(分析)),否則將同步加載JavaScript文件。

就是說,如果腳本文件之間存在依賴性,則文件的加載順序可能很重要。

不,只要腳本標簽是同步加載的,就可以安全地使用$(document).ready() (在大多數情況下,這表示“通常”)。 瀏覽器等待<script>加載后再繼續。 因此, $(document).ready()在源代碼中包含所有<script>標記。

如果腳本標簽包含asyncdefer屬性,則有兩個例外。 先前的含義表示兼容的瀏覽器可以繼續呈現頁面,而后者則表示在頁面完成后將執行腳本。

設置了兩個文件作為測試:

syncscript.html

<html>
<head>
<title></title>
<style type="text/css">
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function(){
    $(document.body).append('<p>window.load has run.');
});
$(document).ready(function(){
    $(document.body).append('<p>document.ready has run.');
});
</script>
</head>
<body>
<p>Page has loaded. Now continuing page load and attempting to load additional script file (after 10 second pause).</p>
<script type="text/javascript">
var p = document.createElement('p');
p.innerHTML = '<p>Inline script preceding jssleep.php file has run.</p>';
document.body.appendChild(p);
</script>
<script type="text/javascript" src="http://jfcoder.com/test/jssleep.php"></script>
<script type="text/javascript">
var p = document.createElement('p');
p.innerHTML = '<p>This is an inline script that runs after the jssleep.php script file has loaded/run.</p>';
document.body.appendChild(p);
</script>
</body>
</html>

jssleep.php

<?php

header("content-type: text/javascript");

sleep(10);

?>
var p = document.createElement('p');
p.innerHTML = '<p>jssleep.php script file has loaded and run following &lt;?php sleep(10); ?>.</p>';
document.body.appendChild(p);

輸出(在Firefox中):

頁面已開始加載。 現在繼續頁面加載,並嘗試加載其他腳本文件(暫停10秒后)。

jssleep.php文件之前的內聯腳本已運行。

jssleep.php腳本文件已加載並在<?php sleep(10)之后運行; ?>。

這是一個內聯腳本,它在加載/運行jssleep.php腳本文件后運行。

$(document).ready()已運行。

$(window).load()已運行。

那是對的。 但是window.onload還需要下載CSS和圖像,因此可能有點過時了。

您可以執行以下操作:

var scriptsToLoad = 0;
// for each script:
s = document.createElement('script');
s.type = "text/javascript";
s.src = "path/to/file.js";
scriptsToLoad += 1;
s.onload = function() {scriptsToLoad -= 1;};
// after all scripts are added in the code:
var timer = setInterval(function() {
    if( scriptsToLoad == 0) {
        clearInterval(timer);
        // do stuff here
    }
},25);

暫無
暫無

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

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