user3571891
user3571891

Reputation: 111

Does document.write from head tag need to wait for window.onload?

I have a big group of websites which has an include() on the <head> tag, this include loads the content from a file which contains javascript code, this code uses document.write().

The code on the browser looks something like this:

<html>
<head>
<script>document.write('stuff');</script>
</head>
<body>
content
</body>
</html>

This seems to work fine but I was wondering if it could fail on some browser/computer, since the head tag is before the body tag, and document.write writes to the body tag. Is it possible that document.write would try to write to the body tag when this tag still wasn't loaded?

Upvotes: 4

Views: 6324

Answers (2)

Quentin
Quentin

Reputation: 943571

Does document.write from head tag need to wait for window.onload?

No, quite the opposite.

The load event will fire when the document is closed. You can't write to a closed document, so calling write would implicitly call open and erase the existing document.

This seems to work fine but I was wondering if it could fail on some browser/computer, since the head tag is before the body tag, and document.write writes to the body tag.

write will write to whereever the script element is, not to the body.

In this case, however, you are writing text content (which cannot appear as a child node to the head element).

This will cause the head element to end (the end tag is optional) and the body to start (the start tag is optional) and the content to be written at the beginning of the body.

</head> <body> will then be treated as invalid HTML and the browser will do its usual efforts to recover from author errors.

You can see the results in a DOM inspector:

enter image description here

Upvotes: 4

Sterling Archer
Sterling Archer

Reputation: 22395

Here is a small test case that shows the answer:

<html>
<head>
<script>
    document.write('stuff'); 
    console.log("document has written from head");</script>
</head>
<body>
<script>
    window.onload = function() {
        console.log("on load function has triggered");
    }
</script>
</body>
</html>

And the output from Chrome Dev Tools console:

document has written from head test.html:3
on load function has triggered test.html:8

So yes, the code in the head section will run before the onload function.

Please note that document.write() is not something you want to be practicing with. In my experience, I've never had to use it. It overwrites the DOM and can be rather nasty if you don't know how it works. You should use the DOM instead.

Upvotes: 2

Related Questions