Javascript: Run "document.write" in createElement script failed
I have a problem with document.write
. Now, I have a page to loa开发者_开发百科d script dynamically. So, I use document.createElement
to create a <script>
. And in the javascript file, I use document.write
to create a dom
or iframe
element. But it does not work in every browser. Why not?
Code in homepage:
var script = document.createElement('script');
script.setAttribute('src', 'http://yoururl/test.js');
document.getElementsByTagName('head')[0].appendChild(script);
Code in script test.js:
(function(){document.write('hello');})();
Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page. This is almost certainly not what you intend to have happen.
http://javascript.about.com/library/blwrite.htm
If you want to create a dom element, do it this way and append it to the document (or element):
var elem = document.createElement('iframe');
elem.src = "http://www.google.com";
document.getElementById('myContainer').appendChild(elem);
https://developer.mozilla.org/en/DOM/document.createElement
You are adding the new script element in the head. Content in the head is not displayed, so even if the document.write call is succeeding, you won't see the text.
If you want content to be displayed, you have to add it to the body (as a child or other descendant) so move the script to the body:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<title>Document.write test</title>
<body>
<div>
<script type="text/javascript">
var script = document.createElement('script');
script.src = 'http://yoururl/test.js';
document.getElementsByTagName('div')[0].appendChild(script);
</script>
</div>
...
</body>
Note that you must still have a valid document after the document.write is finished.
The above does not work in Firefox 5, but does in IE 6. Note the warning about document.write in the HTML5 spec:
This method has very idiosyncratic behavior. In some cases, this method can affect the state of the the HTML parser while the parser is running, resulting in a DOM that does not correspond to the source of the document. In other cases, the call can clear the current page first, as if document.open() had been called. In yet more cases, the method is simply ignored, or throws an exception. To make matters worse, the exact behavior of this method can in some cases be dependent on network latency, which can lead to failures that are very hard to debug. For all these reasons, use of this method is strongly discouraged.**
精彩评论