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 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.
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.).
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.
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.
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
):
window.onload === onload
window.onload !== document.onload
window !== document
The event handler is onload
not document.onload
. It hangs directly off the window
object (which is the default object).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With