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 trialOliver Williams
6,278 PointsWhat 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
Full Stack JavaScript Techdegree Student 17,600 PointsFrom 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.
- A webpage first gets broken into tons of packets with
.write()
. - They each get sent and take the fastest path possible.
- Packets arrive in any order.
- 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:
- If page is finished. Clears the body. Appends message.
- 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.