6

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>
Wayne
  • 56,476
  • 13
  • 125
  • 118
zjmiller
  • 2,529
  • 3
  • 26
  • 30
  • 1
    http://stackoverflow.com/questions/4584373/difference-between-window-loadfunction-and-document-readyfunction – Murali VP Feb 27 '11 at 20:18

2 Answers2

8

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
Wayne
  • 56,476
  • 13
  • 125
  • 118
  • 1
    so is this the right way to think about it: the document object *does* have an onload method... but at no point in the process of loading the page is this method called... but, on the other hand, after loading the page the window's onload method is called... i'm new to javascript and trying to figure out how to conceptualize things – zjmiller Feb 27 '11 at 20:50
  • @zjmiller - Right, you *could* assign a function to `document.onload`, but the browser wouldn't do anything special with that function. The trick is that assigning to `window.onload` triggers special behavior. The `onload` property of `window` just happens to be the place that the browser looks for the function to call once the document loads. – Wayne Feb 27 '11 at 21:02
  • What's the point of having the `onload` property on other elements than `window` then? :q – SasQ Mar 04 '21 at 02:42
1

The event handler is onload not document.onload. It hangs directly off the window object (which is the default object).

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205