Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.write() vs inserting DOM nodes: preserve form information?

Consider two web pages with the following in their body respectively:

<body>
<script>
document.writeln('<textarea></textarea>')
</script>
</body>

and

<body>
<script>
var t = document.createElement('textarea');
document.body.appendChild(t);
</script>
</body>

(think of them as part of something larger, where the textareas have to be generated from JavaScript and can't be hard-coded into the page). They both produce the same output, but the former is considered "bad", while the latter is considered the "right" way to do it. (Right?)

On the other hand, if you type something in the page and then either refresh it, or go somewhere else and hit Back, then in the former case, what you typed in the textarea is preserved, while in the later it is lost. (At least on Firefox.)

Is there a way to use the latter method and still have the useful feature that what the user has typed into a form is saved even if they accidentally hit refresh or come back via the Back button (at least on Firefox)?

like image 385
ShreevatsaR Avatar asked Dec 15 '08 00:12

ShreevatsaR


People also ask

Why is Document write () not recommended anymore?

. write is considered a browser violation as it halts the parser from rendering the page.

What's wrong with document write?

the web browser has to pause the HTML parsing. The web browser is forced to wait for the resource to load AND to be executed. The situation could even be more harmful, as the browser will also have to wait for additional scripts that could be injected subsequently!

Is it good to use document write?

Since document. write() is always available (mostly) it is a good choice for third party vendors to use it to add their scripts. They don't know what environment you're using, if jQuery is or isn't available, or what your onload events are. And with document.

What is the use of Document write () method?

The document. write() method writes a string of text to a document stream opened by document.


1 Answers

I believe the document.write version actually blows away an existing content on the page. Ie, the body and script tags will no longer be there. That is why people usually use appendChild.

Keeping the text or not is very browser specific. I wouldn't bet that Firefox would not change it's behavior on that in a future version, either. I would suggest implementing an alert dialog when the user trys to navigate away from the page and there is unsaved content in edit fields. Usually you would do this with an unload event.

like image 57
Chase Seibert Avatar answered Nov 14 '22 23:11

Chase Seibert