Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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>
like image 623
zjmiller Avatar asked Feb 27 '11 20:02

zjmiller


People also ask

What's the difference between window onload vs document onload?

The general idea is that window. onload fires when the document's window is ready for presentation and document. onload fires when the DOM tree (built from the markup code within the document) is completed.

What is the purpose of window onload?

onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

Is there any difference between body onload () and document ready () function?

The main differences between the two are: Body. Onload() event will be called only after the DOM and associated resources like images got loaded, but jQuery's document. ready() event will be called once the DOM is loaded i.e., it wont wait for the resources like images to get loaded.

Can you have two onload functions?

Unfortunately, you cannot place multiple onload events on a single page. You can nest multiple functions within the one onload call, but what if you need to cascade an onload script across multiple pages, some which may already have an existing onload event? use the addLoadEvent function below.


2 Answers

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
like image 83
Wayne Avatar answered Sep 22 '22 02:09

Wayne


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

like image 37
Quentin Avatar answered Sep 21 '22 02:09

Quentin