14.1 Writing Dynamic Content During Page Loading

NN 2, IE 3

14.1.1 Problem

You want to customize the content of the body based on client settings or cookie data, particularly in a backward-compatible way.

14.1.2 Solution

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:

<script type="text/javascript">
function yourOS( ) {
    var ua = navigator.userAgent.toLowerCase( );
    if (ua.indexOf("win") != -1) {
        return "Windows";
    } else if (ua.indexOf("mac") != -1) {
        return "Macintosh";
    } else if (ua.indexOf("linux") != -1) {
        return "Linux";
    } else if (ua.indexOf("x11") != -1) {
        return "Unix";
    } else {
        return "Computers";
<h1>Welcome to GiantCo Computers</h2>
<h2>We love 
<script type="text/javascript">document.write(yourOS( ))</script>

14.1.3 Discussion

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

Recipe 15.1 for using document.write( ) to display a random slogan on the page; Recipe 15.6 for greeting users with the part of the day in their local time zones.