Document.write
- DW (document.write) 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.
Here's a possible appication of some relevant parts in the comments above. If you want to test this, put the lines below in a file which you can give any name you want; also create two extra files called external.html and external2.html, and put some content / code inside them:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document.write</title>
<script>
function loadDoc(url) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.write(request.responseText)
}
}
request.open("GET", url, false);
request.send();
}
function copy_docwritten(to,from)
{
document.getElementById(to).innerHTML=document.getElementById(from).innerHTML
}
function empty_div(which)
{
document.getElementById(which).innerHTML=''
}
</script>
</head>
<body>
<a onclick="copy_docwritten('div1','docwrite1')">load external1</a>
<a onclick="copy_docwritten('div2','docwrite2')">load external2</a>
<a onclick="empty_div('div1')">empty external1</a>
<a onclick="empty_div('div2')">empty external2</a>
<div id="div1"></div>
<div id="div2"></div>
<div style="position: absolute; display: none">
<div id="docwrite1"><script>loadDoc('external.html')</script></div>
<div id='docwrite2'><script>loadDoc('external2.html')</script></div>
</div>
</body>
</html>