javascript - [removed] error?

2020-01-27 07:59发布

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 ?

4条回答
一纸荒年 Trace。
2楼-- · 2020-01-27 08:24

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 using innerHTML or createElement/createTextNode instead.

From the Mozilla documentation:

Writing to a document that has already loaded without calling document.open() will automatically perform a document.open call. Once you have finished writing, it is recommended to call document.close(), to tell the browser to finish loading the page. The text you write is parsed into the document's structure model. In the example above, the h1 element becomes a node in the document.

If the document.write() call is embedded directly in the HTML code, then it will not call document.open().

The equivalent DOM code would be:

window.onload = function(){
    var tNode = document.createTextNode("TEST");
    document.body.appendChild(tNode);
}
查看更多
不美不萌又怎样
3楼-- · 2020-01-27 08:44

When document is full loaded, any further call to document.write() will override document content. You must use document.close() before calling document.write() to avoid overwriting.

查看更多
唯我独甜
4楼-- · 2020-01-27 08:45
  1. in the first case the word is not written in the body .. it is written in the head
  2. the first one works because the document is still open for writting.. once it has completed (DOM loaded) the document is closed, and by attempting to write to it you replace it ..
查看更多
We Are One
5楼-- · 2020-01-27 08:46

First create an element, for example a div, than add content to the div with window.onload event.

document.write('<div id="afterpostcontent"><\/div>');
window.onload = function()
{
    document.getElementById('afterpostcontent').innerHTML = '<span>TEST<\/span>';
}

You can create an external JavaScript file with this content and just call it anywhere, for example:

<script src="afterpostcontentcode.js"></script>
查看更多
登录 后发表回答