如果使用document.write则无法以编程方式插入js
我试图以编程方式插入 js 文件,使用 jquery 和类似的东西:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'http://someurl/test.js';
$('body').append(script);
它工作正常,如果 test.js 包含 alert
或一些简单的代码,它工作正常,但如果文件 test.js 包含document.write
,并且包含 js 的文件托管在 test.js(或 localhost)之外的另一个域上,没有任何反应,并且 firebug 显示错误:
从异步加载的外部调用 document.write() 脚本被忽略。
如果 test.js 和包含它的文件托管在同一个域上,在 chrome 上它仍然无法工作,但在 firefox 上 document.write
可以正常执行,但页面永远保持“加载”状态并且嗅探器显示对所有处于“待处理”状态的文件的请求。
我还可以尝试哪些其他方法以编程方式包含 js 文件?
I am trying to insert js files programmatically, using jquery and something like this:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'http://someurl/test.js';
$('body').append(script);
It works fine, if test.js contains an alert
or some simple code it works fine, but if the file test.js contains document.write
, and the file including the js is hosted on another domain than test.js (or localhost), nothing happens and firebug shows the error :
A call to document.write() from an asynchronously-loaded external
script was ignored.
If the test.js and the file that include it are hosted on the same domain, on chrome it still wont work but on firefox the document.write
gets executed fine but the page stays "loading" forever and sniffer show request to all the files with "pending" status.
What other methods to include js files programmatically could I try?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
innerHTML
而不是使用document,write
。并使用以下代码来注册脚本,
use
innerHTML
instead of usingdocument,write
.and use following code to register script,
Document.write 仅适用于加载 html 时的同步任务(第一次),绝不适用于您尝试执行的异步任务。
Document.write is ONLY for synchronous tasks when the html is loaded (for the very first time), never for asynchronous tasks like the one you are trying to do.
您想要做的是将
DOM 元素动态插入到 HEAD 元素中。我有这个脚本。举个例子,这是一个竞争条件,但你明白了。使用 URL 调用
load_js
。许多现代 API 都是这样做的,它是跨域 JavaScript 的最好朋友。What you want to do is dynamically insert a
<script>
DOM element into the HEAD element. I had this script sitting around. As an example, it's a race condition, but you get the idea. Callload_js
with the URL. This is done for many modern APIs, and it's your best friend for cross-domain JavaScript.您插入 JavaScript 的方法没有任何问题。
document.write
只是有点糟糕。它仅适用于同步任务,因此将document.write
放在单独的脚本文件中会带来麻烦。无论如何,人们都会这样做。我最常看到的解决方案是覆盖document.write
。There isn't anything wrong with your approach to inserting JavaScript.
document.write
just sucks a little bit. It is only for synchronous tasks, so putting adocument.write
in a separate script file is asking for trouble. People do it anyway. The solution I've seen most often for this is to overridedocument.write
.