Invoking document.write()

亡梦爱人 提交于 2019-12-19 19:34:49

问题


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 error:

Invoking document.write() from asynchronously-loaded external script was ignored.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7255526/invoking-document-write

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!