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>
1

2 Answers 2

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
3
  • 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
    Commented Feb 27, 2011 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
    Commented Feb 27, 2011 at 21:02
  • What's the point of having the onload property on other elements than window then? :q
    – SasQ
    Commented Mar 4, 2021 at 2:42
1

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

1
  • does the document object not have an onload method?
    – zjmiller
    Commented Feb 27, 2011 at 20:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.