14.1 Writing Dynamic Content During Page Loading
NN 2, IE 3
All scriptable browsers let you embed scripted document.write( ) statements anywhere in the body where you want customized content to appear. The following code displays a message tailored to the visitor's operating system:
The preceding solution works on all scriptable browsers. Exercise care, however, when experimenting with document.write( ). When you embed this method in the page flow, as shown in the solution, you do not use the document.open( ) or document.close( ) methods commonly associated with document.write( ). This is because the page-rendering stream is already open by virtue of the page loading from the server; the browser automatically closes the stream when the content ends.
A common beginner's mistake is to try to invoke document.write( ) after the page has loaded in an effort to modify or add to the content on the page. But if you invoke document.write( ) at that point, the current page automatically goes away, taking with it all scripts and data embedded in the page. Invoking document.write( ) by itself equates to three methods in sequence: document.clear( ), document.open( ), and document.write( ). In other words, after the current page has loaded, use document.write( ) only to replace the current page with other content that your scripts assemble (as shown in Recipe 14.2). To modify the existing page (to the extent that your target browsers support this feature), use the more direct element object manipulation shown throughout Chapter 15.
14.1.4 See Also