Window onload Event
By Stephen Bucaro
The onload event executes immediately after the webpage finishes loading. You should
never write code that attempts to access elements on a document before the page
completes loading because the element may not be created yet. The onload event
allows you to access webpage elements immediately after all the coded elements have been created.
Originally the onload event was called in the body tag and it was usually used
to execute some initialization code as shown below.
<head>
<script language="JavaScript">
function init()
{
...
}
</script>
</head>
<body onload="init()">
Today programmer's frown on calling the onload event in the body tag because onload
is technically a window event not specifically related to the body element.
Now, the onload event is usually called near the end of a Java Script code block in
the head section of the webpage as shown below.
<head>
<script language="JavaScript">
function init()
{
...
}
window.onload = init;
</script>
</head>
The problem with the above method is that it allows only one function to be called
by the onload event. The method shown below uses addEventListener which allows
you to add multiple event listeners to the onload event.
if (window.addEventListener) // Netscape/Firefox/Opera
{
window.addEventListener("load", function1, false);
window.addEventListener("load", function2, false);
}
else if (window.attachEvent) // IE
{
window.attachEvent("onload", function1);
window.attachEvent("onload", function2);
}
However Internet Explorer does not recognize addEventListener, it uses attachEvent
instead, and the code above shows you how to make your code compatible with both Firefox and Internet Explorer.
In the last argument of addEventListener, true means you want to use event
capturing and false means you want to use event bubbling. To make a complex
subject simple, when you execute an event on a element that is nested inside another element
(and this is always the case because all elements are nested inside the body element)
and multiple elements have event handlers for the same event, event capturing causes
the outer element to execute its event handler first, bubbling causes the inner element
to execute its event handler first. Internet Explorer supports only event bubbling.
More Java Script Code: • Find a Character or a Substring Within a String • Remove Blank Spaces From Ends of a String • Java Script Character Encoding and Decoding • The while Loop • Java Script Data Types • Comparison Operators • JavaScript .big and .small to Change Text Size • Define Lines in a String • Java Script Events • Window onload Event
|