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)?
. write is considered a browser violation as it halts the parser from rendering the page.
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!
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.
The document. write() method writes a string of text to a document stream opened by document.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With