Reputation: 449
By looking at the output of console.log(document)
, I find document
has these properties:onload=null;onloadstart=null;onloadend=null;onreadystatechange=null;
I write the following code:
<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>
Interestingly, document.onload,document.onloadstart,document.onloadend
are never called, while document.onreadystatechange
is called twice, why?
Upvotes: 2
Views: 199
Reputation: 40882
Why isn't document.onload called?
First of all the load
events (created by the browser) do not bubble (because that's how it is specified):
document.body.onload = function(e) {
console.dir(e.bubbles)
}
So you can only listen for these load
events, on the element for which they occur.
And for Document there is no load
event listed that will be triggered based on the standard.
readystatechange
on the other hand is listed as an event that can happen for document
.
You can however for sure listen for load
events on the document
and the event callback will be called. But that will only happen if you e.g. manually trigger one on document
:
const event = new Event('load');
document.onload = function (e) {
console.log('load document')
}
document.dispatchEvent(event);
Or if you emit a load
event that bubbles on a descendant:
const event = new Event('load', {bubbles: true});
document.onload = function (e) {
console.log('load document')
}
document.body.dispatchEvent(event);
So why does onload
then appear as a property? That's due to the GlobalEventHandlers
and Document includes GlobalEventHandlers
), and due to event handler IDL attribute, exposing those as on…
event properties.
Upvotes: 2
Reputation: 2123
.onload
is part of the window
object, not for document
.
GlobalEventHandlers.onload
The onload property of the GlobalEventHandlers mixin is an event handler that processes
load
events on aWindow
,XMLHttpRequest
,<iframe>
and<img>
elements, etc.
And from what i've seen on MDN .onloadstart
and .onloadend
are used for resources like images, don't know if they are availiable for document
/window
. GlobalEventHandlers.onloadstart
But I think with onreadystatechange
you should be able to emulate the behavior of onloadstart
and onloadend
.
Document.readyState
Upvotes: 1
Reputation: 129
I'm unsure, but try this:
window.addEventListener('load', () => {
alert("document.onload")
})
I only use window onload event, but if I never saw document onload event, just change window
to document
.
Like I said´, I'm unsure what to do, because the amount of your code, which you showed is to less.
Upvotes: 1