Javascript: 在 'onload' 事件之后应用的事件处理程序如何处理页面完全加载之前发生的事件?

Javascript: How can event handler applied after 'onload' event handle events that happened before page was completely loaded?

此代码有效。首先,警告说 'true' 因为图像确实加载了,然后是 'error' 因为图像不存在。但我不明白事件处理程序是如何知道错误的,因为处理程序直到主体加载后才应用(?)到图像。

onload 触发之前不加载图像吗?在我看来,图像尝试加载,失败,然后将处理程序应用于元素,然后处理程序等待,不知道失败已经发生。

<!DOCTYPE html>
<html>
  <head>
    <script>
      function myFunction() {
        alert("Image loaded: " + document.getElementById("myImg").complete);
        document.getElementById("myImg").addEventListener("error", ErrorHappened());
      }
            
      function ErrorHappened(){
        alert('error');
      }
    </script>
  </head>
  <body onload="myFunction()">
            
    <p>This property returns true if the image is finished loaded, and false if not.</p>
            
    <img id="myImg" src="compmanabc.gif"  alt="Computerman" width="107" height="98">
            
  </body>
</html>

因为当您尝试将它添加到事件侦听器时,您实际上是在调用该函数。您应该通过引用传递函数:

document.getElementById("myImg").addEventHandler("error", ErrorHappened);

注意函数名称后没有括号。