3

How exactly does document.write() work?

When I do

  document.write('<script src="file.js"><\/script>');

inside a script tag which is inside a head tag, document.write() inserts the tag within the head tag. (Since I've called it from within head tag)

When document.write is called after the page fully loads, it implicitly calls document.open() and then executes document.write()

My question is, after page load, when I call

document.write('hello');  //Inserts 'hello' within body tag

and when I call

document.write('<script src="file.js"><\/script>'); //Inserts within head tag

So how exactly does document.write() know what kind of string am I inserting? Does it parse the string too?

Parth
  • 568
  • 2
  • 6
  • 23

1 Answers1

4

The browser treats all data inserted by document.write as if it came from the server, right after the script block which contains the write. So, if you document.write('<script>alert(1);</' + 'script>');, the browser will add another <script> element after the current one. Script blocks are executed no matter where they are, in the head or in the document body.

If the call to document.write happens after the page is loaded, a new document will be created.

Your third snippet will create an HTML document containing only a <script> tag. This is not valid HTML, so most browsers will magically create the <html> and <head> elements for you, and place the script element there.

Mihai
  • 2,835
  • 2
  • 28
  • 36