Question: I'm learning JavaScript from w3schools and it talks about how "If you execute document.write after the document has finished loading, the entire HTML page will be overwritten" and I've seen from examples that this does in fact happen, but "I don't understand what is really going on and the website kind seems to skip over the explanation. I've moved parts of the script around (

```
<h1>My First Web Page</h1>

<p>My First Paragraph</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
document.write("Oops! The document disappeared!");
}
</script>

</body>
</html>

```

)

To see if loading different parts from different points in the script would change the effect, and nothing happened. 

I'd like to know what is really going on before I continue with the lesson, so if anyone can even just give me a brief summary of how it works I'd appreciate it.

Answer: 
If you're familiar with programming in general then you'll be aware of `stream`s, which represent something you can read from, or write to, in continuous fashion and (usually) lack random-access.

Imagine that the `document` object contains hidden inside it a stream that represents the raw text response from the webserver which consists of the HTML text. The method `document.open()` grants access to this stream.

When a page is being loaded (right as the bytes from the server arrive in your browser) the document stream is already opened and is being read from/written to. When the document has finished loading (that is, the HTML itself, not external resources like `<img />`) the stream is closed.

...that's why when `document.write` is used while the page is loading (i.e. as `<script>document.write("foo");</script>` it inserts the text "foo" directly into the document stream, whereas calling `document.write` *after* the document has loaded causes the stream to be (implicitly) re-opened from the beginning, which causes it to be overwritten.
What happens depends on what browser you are using. Until recently your code would replace the page with the text in all browsers, but lately the implementation has changed in some browsers to simply ignore the `document.write` call instead of implicitly calling `document.open` first if it hasn't been called already.

You can still use `document.write` after the page has loaded to replace the page in all browsers, but then you have to do it in the correct way, i.e. calling `document.open` first.