It is common place to place the JavaScript (preferably in a link to an external file) at the bottom of the page. However, there may be times when the code needs to placed before the html content, but this can cause an issue since the JavaScript  may be setting values that cannot be recognised by the script as the page contents, and therefore any elements, have not been loaded.


To overcome this issue, the .onload method can be called upon the window (top level browser object) which can be assigned to an anonymous function that calls any specified named functions upon the whole contents of the window (i.e. the document) being loaded:

			function loadEventHandlers(){

				var myElement = document.getElementById("myId");
				myElement.onclick = function(){
					alert("You clicked myElement");

			window.onload = function(){
		<h1 id="myId">onclick can be applied to any element</h1>
		<p>This page is using window.onload to load the script once the whole window has been loaded</p>

*note: window.onload should only be used once within a page

Leave a Reply