Join the Discussion
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.
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:
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:
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.