简体   繁体   中英

Why does window.onload work while document.onload doesn't?

Can anyone tell me why the following page doesn't trigger an alert when it loads? If I use window.onload instead of document.onload it works. Why is there this difference?

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

document.onload = function() {
    alert('Test');
}

</script>
</head>
<body>
</body>
</html>

The simplest answer is that it just wasn't designed that way. The browser executes the function attached to window.onload at the " end of the document loading process ". It does not attempt to execute a function attached to document.onload .

You could assign a function to document.onload but the browser will not do anything special with it.

Some things to keep in mind (assuming you've just assigned a function to one or the other of window.onload or document.onload ):

  1. window.onload === onload
  2. window.onload !== document.onload
  3. window !== document

The event handler is onload not document.onload . It hangs directly off the window object (which is the default 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