10

This is a very basic question. I have this script:

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

It shows my complete page. And at the end of page Hello2 will be displayed. But when ever I go to developer tools and call write(), it will replace my entire body html. Just curious to know.

        window.onload=write;// has the same effect. Clear's my page.

Thanks.

Akhil Sekharan
  • 11,581
  • 6
  • 34
  • 54

3 Answers3

17

When the document is being read and parsed by the browser, if there's a script element that calls document.write, the output of document.write is inserted into the document at that point. Later, though, once the page is fully loaded, if you use document.write, it implicitly performs a document.open, which wipes out the page and starts writing a new one from scratch.

More on MDN:

In general, rather than using document.write to add content to a page, use the various DOM methods (either directly, or via a library like jQuery, YUI, Closure, or any of several others).

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • What do you mean by "once the page is fully loaded"? How is it defined? Is it guaranteed that the "page is fully loaded" before ` – Pacerier Oct 11 '14 at 14:34
  • @Pacerier: "What do you mean by "once the page is fully loaded"?"* The parser has reached the end of the document. *"Is it guaranteed that the "page is fully loaded" before – T.J. Crowder Oct 11 '14 at 21:11
  • is this behavior documented or does it merely "seems to be how it works"? – Pacerier Oct 12 '14 at 05:50
  • @Pacerier: Which behavior? `document.write`? The `load` event? I mean, the answer is yes, it's just a matter of what spec to point you at. – T.J. Crowder Oct 12 '14 at 06:55
  • The behavior that `document.write` will surely rewrite the entire page if it's placed in `body onload`. – Pacerier Oct 12 '14 at 07:46
  • @Pacerier: That would be the Web APIs section of [the HTML5 specification](http://www.w3.org/TR/html5/webappapis.html#document.write()). – T.J. Crowder Oct 12 '14 at 07:48
  • This is an evil feature, very had to debug if `document.write()` is sprinkled somewhere in your event handler – Dheeraj Aug 08 '19 at 07:17
7

When it is executed after the page has completed loading, it overwrites the entire content - one of the points raised in the answer to this question: Why is document.write considered a "bad practice"?

Community
  • 1
  • 1
Chamila Chulatunga
  • 4,626
  • 13
  • 17
0

document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.

MadhuriJain
  • 95
  • 1
  • 4