1. Computing

Using window.onload

Join the Discussion

Questions? Comments?

Some scripts require that you run something immediately after the web page finishes loading. The normal way to do this is to add an onload attribute to the body tag. You don't have to do it that way though, you can set up a global event handler to do it instead.

Why would you want to use a global event handler instead of just adding the code into the body tag? I can think of two reasons. Firstly by using a global event handler you make it easier to add the code to web pages because you don't have to edit the body tag, if you add the script into an existing external Javascript file attached to your page you may not need to edit the page at all. Secondly some web editors may limit your ability to add code easily to the body tag.

There is one change that you might have to make in converting your code to use a global onload event handler. The global even handler requires that it call a function and not execute code directly. The reason for this is that we want to run the code after the page is loaded because we probably want to refer to the page content itself and we can't do that until that content exists to be referenced.

Let's look at a simple example of how to convert to using the global onload. Here is code that sets first focus to the first input field of the first form on the page:

<body onload="document.getElementsByTagName('input')
continued from previous line[0].focus();" >

The input field doesn't exist until the page is loaded and so we place the code to set the focus to that field into a function and call the function from the global event handler like this:

function init() {
document.getElementsByTagName('input')[0].focus();
}
window.onload = init;

This code tells the page to run the init function when the page finishes loading so the field exists by the time that the function is run.

You can make similar changes to get the global onload handler to run any code that you might have otherwise put into the body tag simply by inserting it into the init function.

Related Video
Using Meta Data for Search

©2014 About.com. All rights reserved.