Invoking document.write()

这一生的挚爱 提交于 2019-12-01 17:45:41

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.

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