Demo of document.write() & "how" it works

The two examples below, hopefully, illustrate some of the issues associated with document.write().

<BODY onLoad="somefunction()"> tells the browser to run the function after the document is already loaded. When the onLoad Event Handler is invoked, you can be certain that the document is fully loaded, and therefore that all scripts within the document have executed, all functions within the scripts are defined, and all forms and other document elements have been parsed and are available through the Document Object.

Understanding the sequencing of how a browser interprets statements is important. The browser always starts at the top and starts to parse (or interpret) the lines, line by line. Where we can get in trouble is when we refer to "something" before it exist. One way to solve this problem is to use the onLoad within the <BODY> tag, this insures us that when we refer to "something" - we know that it already exist.

The second example demonstrates some of the problems of using document.write(). First, the page gets loaded, this means that document's visible items are displayed and the document's "invisible" items are stored in memory ready for use. When getName() gets called it initiates 3 steps:

  1. prompts the user for their name
  2. puts their name into the text field
  3. then document.write() overwrites the entire document with the following:

    <H2><CENTER><FONT COLOR="navy">
    Frank, try a variation of this page for yourself.
    </FONT></CENTER></H2>

If you view the source within the IE 4.x or greater all you see is:

<H2><CENTER><FONT COLOR="navy">
Frank, try a variation of this page for yourself.
</FONT></CENTER></H2>

So the punchline is -- Think through the sequencing of all your code.