简体   繁体   中英

load event doesn't work with addEventListener but works with onload property

const body = document.querySelector("body");

body.addEventListener("load", () => {
  console.log("test");
});

body.onload = () => {
  console.log("test");
};

when i use only addEventListener i don't see the message in the console but if i use onload property or use onload attribute in the html it works

This is because the load event is part of what is called the Window-reflecting body element event handler set .
Basically, these events are also accessible as HTML attributes and IDL attributes on the <body> element, even though the primary target is actually the Window object.

This is done because historically we had to use HTML attributes to set event handlers, and setting the load event in the <body> tag was more "natural". Since then we have gotten far better ways to set up event handlers and we can define clearly that this event fires on the Window object, which is more logical.
However browsers still need to support code that was listening to the onload="" HTML attribute, so this reflection thing has been set up.
Note that it's not just adding a new event listener, the event actually only fires on the Window object, but the handler can be set from the <body> , even overriding the ones already set on the Window object.

 window.onmessage = (evt) => console.log("handled a message from Window, is Window the currentTarget:", evt.currentTarget === window); document.body.onmessage = (evt) => console.log("handled a message from body, is Window the currentTarget:", evt.currentTarget === window); postMessage("hello", "*");

EventTarget#addEventListener() has no means to do this retargetting, so when you do document.body.addEventListener("load", cb) , you are really waiting for an event that will go through the <body> element, but as demonstrated above, the event actually only fires on the Window object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM