document.onLoad 与 Body标签中加入onLoad 和 windows.onload

qinMS903 -
document.onLoad 与 Body标签中加入onLoad 和 windows.onload
问题: 我一直认为使用javascript的document.onLoad指定一个函数,跟在Body标签中加入onLoad是一样的 不过能过今天的示例发现,document.onLoad并不是在页面加载完成时引发。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

<head>

  <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
  <title>无标题文档</title>
  <script language="JavaScript">
    function mytest1() {
      console.log('document', new Date())
      console.log('document', document.querySelector('body'))
      // alert(document.getElementById("my2"));
      console.time()

    }
    document.onLoad = mytest1();

    function mytest2() {
      console.log('body', new Date())
      console.log('body', document.querySelector('body'))
      console.log('body img', document.querySelector('img'))
      console.timeEnd()
      console.time()
      // alert(document.getElementById("my2"));
    }
    function mytest3() {
      console.log('img', new Date())
      console.log('img', document.querySelector('img'))
      console.timeEnd()
      // alert(document.getElementById("my2"));
    }

  </script>
</head>

<body onload="mytest2()">
  <p id="my2" >测试内容</p>
  <img onload="mytest3()" src="./logo.png"/>
</body>

</html>

调用 docuemnt.onload 指的是这个文档元素加载完成时,仅当DOM加载完成,不包括它子元素,
他们的顺序是 docuemnt.onload > body 内部的元素的onload > body onload

而且,windows.onload 就是 body onload 因为,他们应该是同一个方法

body 标签上的 onload="mytest2()" 方法会覆盖,windows.onload 赋值方法
如果,windows.onload 是在 加载完成body 标签之后赋值的 会覆盖 body 标签上的 onload 方法

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

<head>

  <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
  <title>无标题文档</title>
  <script language="JavaScript">
    function mytest1() {
      console.log('document', new Date())
      console.log('document', document.querySelector('body'))
      // alert(document.getElementById("my2"));
     
    }
    document.onLoad = mytest1();

    function mytest2() {
      console.log('body', new Date())
      console.log('body', document.querySelector('body'))
      console.log('body img', document.querySelector('img'))
    
      // alert(document.getElementById("my2"));
    }
    function mytest3() {
      console.log('img', new Date())
      console.log('img', document.querySelector('img'))
      
      // alert(document.getElementById("my2"));
    }

    window.onload = function(){
      console.log('window', new Date())
    }
  </script>
</head>

<body onload="mytest2()">
  <p id="my2" >测试内容</p>
  <img onload="mytest3()" src="./logo.png"/>
</body>

</html>  
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

javascripthtmlhtml5前端

扩展阅读

加个好友,技术交流

1628738909466805.jpg