簡體   English   中英

為什么不調用 document.onload?

[英]Why isn't document.onload called?

通過查看console.log(document)的輸出,我發現document具有以下屬性: onload=null;onloadstart=null;onloadend=null;onreadystatechange=null; 我寫了以下代碼:

<html>
<head><title>test</title></head>
<body>
<script>
document.onload=function(){alert("document.onload");};
document.onloadstart=function(){alert("document.onloadstart");};
document.onloadend=function(){alert("document.onloadend");};
document.onreadystatechange=function(){alert("document.onreadystatechange");};
</script>
<div>hello</div>
</body>
</html>

有趣的是, document.onload,document.onloadstart,document.onloadend從來沒有被調用過,而document.onreadystatechange被調用了兩次,為什么?

為什么不調用 document.onload?

首先, load事件(由瀏覽器創建)不會冒泡(因為它是這樣指定的):

 document.body.onload = function(e) { console.dir(e.bubbles) }

因此,您只能在它們發生的元素上偵聽這些load事件。

對於Document ,沒有列出將根據標准觸發的load事件。

另一方面, readystatechange被列為document可能發生的事件。

但是,您可以肯定地監聽document上的load事件,並且將調用事件回調。 但這只有在您手動觸發document時才會發生:

 const event = new Event('load'); document.onload = function (e) { console.log('load document') } document.dispatchEvent(event);

或者,如果您發出一個在后代上冒泡的load事件:

 const event = new Event('load', {bubbles: true}); document.onload = function (e) { console.log('load document') } document.body.dispatchEvent(event);

那么為什么onload會作為一個屬性出現呢? 這是由於GlobalEventHandlersDocument includes GlobalEventHandlers ),並且由於事件處理程序 IDL 屬性,將它們公開為on…事件屬性。

.onloadwindow對象的一部分,而不是document GlobalEventHandlers.onload

GlobalEventHandlers mixin 的 onload 屬性是一個事件處理程序,用於處理WindowXMLHttpRequest<iframe><img>元素等上的load事件。

從我在 MDN 上看到的.onloadstart.onloadend用於圖像等資源,不知道它們是否可用於document / window GlobalEventHandlers.onloadstart

但我認為使用onreadystatechange您應該能夠模擬onloadstartonloadend的行為。
Document.readyState

我不確定,但試試這個:

window.addEventListener('load', () => {
    alert("document.onload")
})

我只使用 window onload 事件,但如果我從未見過 document onload 事件,只需將window更改為document

就像我說的那樣,我不確定該怎么做,因為您顯示的代碼量要少。

暫無
暫無

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

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