DOMContentLoaded与onload加载顺序

本文详细介绍了DOM事件中的load和DOMContentLoaded事件的区别及使用方法。load事件在文档及其所有资源加载完成后触发,而DOMContentLoaded则在DOM构建完成后立即触发,无需等待其他资源加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. window.onload = function() {   
  2.   init();   
  3.   doSomethingElse();   
  4. };  
  1. <!doctype html>  
  2.   <html>  
  3.   <head>  
  4.     <title>onload test</title>  
  5.     <script>  
  6.       function load() {   
  7.         alert("load event detected!");   
  8.       }   
  9.       window.onload = load;   
  10.     </script>  
  11.   </head>  
  12.   <body>  
  13.     <p>The load event fires when the document has finished loading!</p>  
  14.   </body>  
  15. </html>  


The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

There are also Gecko-Specific DOM Events like DOMContentLoaded and DOMFrameContentLoaded (which can be handled using element.addEventListener() ) which are fired after the DOM for the page has been constructed, but do not wait for other resources to finish loading.


以上引用:https://developer.mozilla.org/en/DOM/window.onload


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>addEventListener增加事件监听</title>
<style type="text/css">
.t{border: 1px solid red;width:100%;border-collapse:collapse;border-sapcing:0px;}
#t1{background-color:pink;}
</style>
<script type="text/javascript">
function modifyText () {
// Function to change the content of t2
var t2 = document.getElementById("t2");
t2.firstChild.nodeValue = "three";
}


function load () {
// Function to add event listener to t
var el = document.getElementById("t");
el.addEventListener("click",modifyText,false);
}
document.addEventListener("DOMContentLoaded",load,false);
</script>
</head>
<body>
   <table class="t" id="t">
         <tr>
              <td id="t1">one</td>
         </tr>
         <tr>
              <td id="t2">two</td>
         </tr>
   </table>
</body>
</html>

DOMContentLoaded,是dom构建好后调用,但不等其他资源加载好

onload等所有的资源加载完调用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值