Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Oliver Williams
Oliver Williams
6,278 Points

What is the point of document.open() and document.close() in JavaScript?

Are they only used with document.write? Doesn't document.write work all by itself without them? If it is bad practice to use document.write does that mean open() and close() have no good use cases?

1 Answer

jobbol
seal-mask
.a{fill-rule:evenodd;}techdegree
jobbol
Full Stack JavaScript Techdegree Student 17,600 Points

From a server perspective

Interesting question. All of these functions use a syntax that most developers are familiar with. Generally you'd use them all like this.

//first open the document stream for writing commands.
document.open();  

//write something
document.write('<h1>Webpage</h1>'); 

//you can continue sending more writes
document.write('<p>Hello world!</p>');  

//close the stream so it renders to the browser.
document.close(); 

Don't quote me on this, but I believe the front end was influenced by the back end. The reason we'd use this system is because it follows the same steps as the server sending a webpage.

  1. A webpage first gets broken into tons of packets with.write().
  2. They each get sent and take the fastest path possible.
  3. Packets arrive in any order.
  4. Once all packets arrive, the original message is reassembled and the webpage is rendered .close().

Without write and close, we could blindly put the page back in the wrong order. The packets also don't follow any rules on where they break the page. It could be in the middle of a src attribute, and then you'd have images that didn't load.

From a front-end perspective

Document.write will still work without open and close. Write will automatically open and close the stream when it needs to. So forget about everything you just saw above. However, the problem is write acts differently depending on when it is called:

  1. If page is finished. Clears the body. Appends message.
  2. If page is loading. Appends message to end of body.

I find write is good for testing quick dirty things, but not for polished code. Firefox for instance does not automatically call close. So use it with caution.