Invoking document.write()
This code does not work:
<div class="pix"><div id="addTimestamp"></div></div>
<script type="text/javascript">
(function () {
var date = new Date(),
timestamp = date.getTime(),
newScript = document.createElement("script");
newScript.type = 'text/javascript';
newScript.src = 'someUrl=' + timestamp + '?';
document.getElementById('addTimestamp').appendChild(newScript);
}())
</script>
The dynamic script adds document.write(someCode which loads banners)
. But in Firebug I have an erro开发者_开发知识库r:
Invoking document.write() from asynchronously-loaded external script was ignored.
Add this:
newScript.async = false;
Your script needs to load synchronously for document.write()
to work (see https://developer.mozilla.org/En/HTML/Element/Script#attr-async). As you have it now, the script will load whenever the browser has time for it - so you cannot know where your HTML from document.write()
will be inserted. The browser decided to ignore your document.write()
call to prevent worse issues.
document writing javascript causes the html parser to fail when seeing try
document.getElementById('addTimestamp').innerHTML = '<script type="text/javascript" src="someUrl=' + timestamp + '?"' + 'charset="utf-8"></sc' + 'ript>';
However if you want to insert a script tag in in the DOM you need to also be certain the DOM is loaded.
Levon, it seems like you are trying to overcome problems with page load speed (I don't see other reasons not to just insert script statically).
Wladimir's answer is good and valid, but see my comment to his answer.
Another approach, which works, but should be very carefully implemented, is to overwrite the document.write itself. It is very, very, subtle work, it need to be thoroughly tested, but it can be done, actually. Each call of document.write can store something to some sort of string buffer. Then, by deciding somehow that it is time to flush all the content, just insert all buffers content to some DOM element.
Works, but very pervy. The best option is not touse document.write at all. But, alas, it is not always the option.
精彩评论