Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
366 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...