The basic concept of window.onload is that its for functions and methods that are needed when the DOM has fully loaded. Say for instance you try to select an element(s) on the page before it has fully loaded the DOM using document.getElementById() this would cause an undefined error and end the script where as window.onload waits for the DOM to fully load before executing the code inside the "anonymous" function.
If your still a little confused see the example below
HTML Code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<title>Javascript Example</title>
<script type="text/javascript">
//<![CDATA[
// This will NOT work due to the DOM not been fully
// loaded yet!
var ele = document.getElementById('myDiv');
alert(ele.innerHTML);
// This will work because the window.onload method waits
// for the DOM to be fully loaded
window.onload = function() {
var ele = document.getElementById('myDiv');
alert(ele.innerHTML);
};
//]]>
</script>
</head>
<body>
<div id="myDiv">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
</body>
</html>
Bookmarks