Document.write again
by
, 05-09-2017 at 08:16 PM (50968 Views)
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.
Comment:
XHTML is a dead duck, so consider changing your DOCTYPE.
DW executed after the page has finished loading will overwrite the page.
Comment:
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.
Comment:
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>
</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.
Comment:
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.
Comment:
When this turns out to be a problem, simply put the invisible writing blocks (see above) just before the closing body tag.
FURTHER READING HERE.