onLoad event handler, delays execution of the script until every component of the document -- not just the script -- has been loaded. I will describe both methods in this article.
When, exactly, is a document loaded? Most browsers let you see portions of a document even before the entire document has finished loading. Netscape Navigator and Internet Explorer, for example, allow you to see a document's text while the images are still on the way. Many scripts can be safely executed before the document has been completely loaded. Other scripts, however, cannot run correctly unless the entire document, including images, is loaded before the script starts.
I will now describe two techniques for automatically executing a script on a web pages. Before deciding which one is right for your page, you must first determine when it is safe to execute your script. I'll leave that decision to you.
To execute a script after loading the text, but perhaps before the images, simply include a "starter script" at the end of the document, as shown below:
In this example, the function<html> <head>...header stuff...</head> <body> . . . (document body) . . <script> start_my_script (); </script> </body> </html>
start_my_scriptwill be called immediately after the document body has been loaded. The script will not wait for images to finish loading.
onLoadevent handler. The code for this event handler must be included in the opening
<body>tag, as shown below:
Even though the browser sees the<html> <head>...header stuff...</head> <body onLoad="start_my_script ();"> . . . (document body) . . </body> </html>
onLoadevent handler before the document body and images are loaded, the code will not actually be executed until after the entire document, including images, has loaded.
Other than this, there is no difference between the code in this example and the code in the previous example.
Note that since a window object cannot have more than one
method 1: method 2: both methods: . . . . . . <script> start_script_1 (); start_script_2 (); </script> </body> </html> . . . <body onLoad="start_script_1 (); start_script_2 ();"> . . . . . . . . . <body onLoad="start_script_2 ();"> . . . <script> start_script_1 (); </script> </body> </html>
onLoadevent handler, the following code is incorrect and will result in only the first script being executed:
. . . <body onLoad="start_script_1 ();"> <body onLoad="start_script_2 ();"> . . . (incorrect, do not imitate!)
March 8, 1997