11

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.

3 Answers 3

20

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).

7
  • 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 <body onload runs?
    – Pacerier
    Oct 11, 2014 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 <body onload runs" Yes. The load event on body happens very late in the page load process. Oct 11, 2014 at 21:11
  • is this behavior documented or does it merely "seems to be how it works"?
    – Pacerier
    Oct 12, 2014 at 5: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. Oct 12, 2014 at 6:55
  • The behavior that document.write will surely rewrite the entire page if it's placed in body onload.
    – Pacerier
    Oct 12, 2014 at 7:46
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"?

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.