IV.1. Writing Variable ContentWhile a page is loading, you can use the JavaScript document.write( ) or document.writeln( ) methods to fill in content that cannot be stored as part of the document. Example IV-1 demonstrates a simple combination of hardwired HTML with dynamically written content to fill a page. In this case, the dynamically written content consists of properties that the client computer and browser can determine without burdening the server. The user is oblivious to the fact that a script creates some of the text on the page. Example IV-1. Combining fixed and dynamic content in a rendered page
You can use document.write( ) or document.writeln( ) in scripts that execute while a document is loading, but you cannot use either method to modify only a portion of a page that has already loaded. Once a document has finished loading, if you make a single call to document.write( ) directed at the current document, the call automatically clears the current document (and scripts) from the browser window and writes the new content to the page. So, if you want to rewrite the contents of a page, you must do so with just one call to the document.write( ) method. Example IV-2 demonstrates how to accumulate content for a page in a variable that is written in one blast when the user clicks a button. Example IV-2. Creating a new document for the current window
Notice that the script inserts data from the original screen's form into the content of the new page, including a new title that appears in the browser window's title bar. As a convenience to anyone looking at the source of the new document, escaped newline characters (\n) are inserted for cosmetic purposes only. After the call to document.write( ), the rewritePage( ) function calls document.close( ) to close the writing stream for the new document. While there are also document.open( ) and document.clear( ) methods, we don't need to use them to replace the contents of a window. The one document.write( ) method clears the old content, opens a new output stream, and writes the content. Both examples are written in such a way that they work in scriptable browsers back to Netscape 2. Thus, the <script> tags include both the old-fashioned language attribute, as well as the more modern type attribute. The <form> tag's onsubmit event handler simply prevents a press of the Enter key in the one-field form from "submitting" the form (which, because of the lack of an action attribute, would cause the page to reload itself). Note, however, that Examples IV-1 and IV-2 require a script-enabled browser to display the dynamic content. You obviously don't want to use this technique for mission-critical page content if non-scriptable browsers may be used to access it. |