Consider the script..
<html>
<head>
<script type="text/javascript">
document.write('TEST');
</script>
</head>
<body>
Some body content ...
</body>
</html>
This works fine and the word 'TEST' is added to the <body>
But when
<script type="text/javascript">
window.onload = function(){
document.write('TEST');
}
</script>
is used, then the body content is fully replaced by the word 'TEST' i.e, the old body contents are removed and ONLY the word 'TEST' is added.
This happens only when document.write
is called within window.onload
function
I tried this in chrome. Is there any mistake made by me ? any suggestions ?
document.write()
is unstable if you use it after the document has finished being parsed and is closed. The behaviour is unpredictable cross-browser and you should not use it at all. Manipulate the DOM usinginnerHTML
orcreateElement
/createTextNode
instead.From the Mozilla documentation:
The equivalent DOM code would be:
When document is full loaded, any further call to
document.write()
will override document content. You must usedocument.close()
before callingdocument.write()
to avoid overwriting.First create an element, for example a div, than add content to the div with
window.onload
event.You can create an external JavaScript file with this content and just call it anywhere, for example: