views:

56

answers:

3

Hello,

Consider the script..

<html>
<head>
   <script type="text/javascript">
        document.write('TEST');
   </script>
</head>

<body>
    Some body content ...
</body>

</html>

This works fine and the word 'TEST' is added to the <body>

But when

<script type="text/javascript">
    window.onload = function(){
        document.write('TEST');
    }
</script>

is used, then the body content is fully replaced by the word 'TEST' i.e, the old body contents are removed and ONLY the word 'TEST' is added.

This happens only when document.write is called within window.onload function

I tried this in chrome. Is there any mistake made by me ? any suggestions ?

+5  A: 

document.write() is unstable if you use it after the document has finished being parsed and is closed. The behaviour is unpredictable cross-browser and you should not use it at all. Manipulate the DOM using innerHTML or createElement/createTextNode instead.

From the Mozilla documentation:

Writing to a document that has already loaded without calling document.open() will automatically perform a document.open call. Once you have finished writing, it is recommended to call document.close(), to tell the browser to finish loading the page. The text you write is parsed into the document's structure model. In the example above, the h1 element becomes a node in the document.

If the document.write() call is embedded directly in the HTML code, then it will not call document.open().

The equivalent DOM code would be:

window.onload = function(){
    var tNode = document.createTextNode("TEST");
    document.body.appendChild(tNode);
}
Andy E
+1  A: 
  1. in the first case the word is not written in the body .. it is written in the head
  2. the first one works because the document is still open for writting.. once it has completed (DOM loaded) the document is closed, and by attempting to write to it you replace it ..
Gaby
A: 

When document is full loaded, any further call to document.write() will override document content. You must use document.close() before calling document.write() to avoid overwriting.

Thevs