View RSS Feed


Document.write again

Rate this Entry
I know, I know... We should not recommend the use of document.write (DW). But not all uses of it are necessarily bad. There are even instances where it is definitely useful, see this. And there's a solution for many problems that people relate to the use of DW. Here's my small contribution to a discussion that is not dead yet:

DW is bad because it does not work in XHTML.
XHTML is a dead duck, so consider changing your DOCTYPE.

DW executed after the page has finished loading will overwrite the page.
Make it run invisibly while the page is still loading then apply the method below.

DW executes where encountered: it cannot inject at a given node point.
This problem can be dealt with. Make DW run invisibly while the page is still loading (see above), like this:
<div style="position: absolute; display: none">
<div id="docwritten"><script>YOUR DOCWRITE HERE</script></div>
then use innerHTML to copy the docwritten content to any div you want, for example:
<a onclick="document.getElementById('some_div').innerHTML=document.getElementById('docwritten').innerHTML">push DW-content to a specific place</a> .
If your docwritten content is an external file (your domain), then the use of innerHTML for pushing it to a specific place(see above) wil not destroy any code present in the external file since it is already docwritten to your page.

DW is writing serialized text which is not the way the DOM works conceptually.
This kind of objections does not prevent most of us from using innerHTML and JSON!

DW prevents the browser from processing the parts of the page that follow the writing block.
When this turns out to be a problem, simply put the invisible writing blocks (see above) just before the closing body tag.


Submit "Document.write again" to Submit "Document.write again" to StumbleUpon Submit "Document.write again" to Google Submit "Document.write again" to Digg

Updated 05-10-2017 at 08:23 AM by molendijk

Tags: None Add / Edit Tags


  1. molendijk's Avatar
    See also document-write to a specific place after page load, which is an elaboration of my post.