如果使用document.write,则无法以编程方式插入js [英] Can't insert js programmatically if it uses document.write

查看:410
本文介绍了如果使用document.write,则无法以编程方式插入js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以编程方式插入js文件,使用jquery和类似的东西:

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);

如果test.js包含警报或一些简单的代码,它工作正常,但如果文件test.js包含 document.write ,并且包含js的文件托管在另一个域而不是测试。 js(或localhost),没有任何反应,firebug显示错误:

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 :


从异步加载的外部调用document.write()
脚本被忽略。

A call to document.write() from an asynchronously-loaded external script was ignored.

如果test.js和包含它的文件托管在同一个域上, Chrome仍然无法正常工作,但在firefox上 document.write 执行得很好,但页面永远保持加载状态,并且嗅探器向所有处于挂起状态的文件显示请求。

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.

我可以尝试以编程方式包含js文件的其他方法吗?

推荐答案

使用 innerHTML 而不是使用文件,写

并使用以下代码注册脚本,

and use following code to register script,

(function() {
    var jq = document.createElement('script');
    jq.type = 'text/javascript';
    jq.async = true;
    jq.src = 'http://someurl/test.js';
    var s = document.body.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(jq, s);
})();

这篇关于如果使用document.write,则无法以编程方式插入js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆