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 simplest answer is that it just wasn’t designed that way. The browser executes the function attached to
window.onloadat the “end of the document loading process“. It does not attempt to execute a function attached todocument.onload.You could assign a function to
document.onloadbut 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.onloadordocument.onload):window.onload === onloadwindow.onload !== document.onloadwindow !== document