[英]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
會作為一個屬性出現呢? 這是由於GlobalEventHandlers
和Document includes GlobalEventHandlers
),並且由於事件處理程序 IDL 屬性,將它們公開為on…
事件屬性。
.onload
是window
對象的一部分,而不是document
。 GlobalEventHandlers.onload
GlobalEventHandlers mixin 的 onload 屬性是一個事件處理程序,用於處理
Window
、XMLHttpRequest
、<iframe>
和<img>
元素等上的load
事件。
從我在 MDN 上看到的.onloadstart
和.onloadend
用於圖像等資源,不知道它們是否可用於document
/ window
。 GlobalEventHandlers.onloadstart
但我認為使用onreadystatechange
您應該能夠模擬onloadstart
和onloadend
的行為。
Document.readyState
我不確定,但試試這個:
window.addEventListener('load', () => {
alert("document.onload")
})
我只使用 window onload 事件,但如果我從未見過 document onload 事件,只需將window
更改為document
。
就像我說的那樣,我不確定該怎么做,因為您顯示的代碼量要少。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.