javascript - 动态包含 javascript 文件中的 javascript 代码

标签 javascript dynamic

我将以下脚本(位于我自己的服务器上)插入到第三方的外部页面:www.test.com/test.html:

<script type="text/javascript">
(function() {
  var protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
  var ttScript = document.createElement('script');ttScript.async = true;
  ttScript.src = '//www.example.com/script/mycode.js';
  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ttScript);
})();
</script>

这是我要动态注入(inject)的另一个脚本,请注意,它不能只添加到上面的脚本中!我希望这个脚本是动态可用的。 完整的代码稍后将存储在对象 message.jsScript

<script type="text/javascript">
var tt_totalordervalue;
function tt_getordervalue(){
    tt_totalordervalue=$('#subtotal');
    console.log(tt_totalordervalue);
}
</script>

在文件 mycode.js 中:

我想动态添加上面的脚本并调用其中定义的函数tt_getordervalue,我现在尝试按如下方式执行此操作。请注意,我还想将动态脚本中定义的变量 tt_totalordervalue 的值分配给我的 mycode.js 中的变量:

(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(message.jsScript);
console.log('script added');
tt_getordervalue();
console.log('function called');
var val = tt_totalordervalue;

但是,我收到错误 Uncaught NotFoundError: Failed toexecute 'appendChild' on 'Node': The new child element is null.

为什么?

最佳答案

以下在 Mac 上的 chrome 上运行(抱歉,懒得交叉测试):

var script = document.createElement('script');
script.innerHTML = 'window.doStuff = function(){alert("do")}';
document.getElementsByTagName('body')[0].appendChild(script);
doStuff();

关于javascript - 动态包含 javascript 文件中的 javascript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26331777/

相关文章:

HTML CSS 表格布局

javascript - 为什么我在 div JavaScript 中得到额外的正斜杠

Java在滚动条出现时动态改变组件

javascript - 有没有不用图片用HTML5 canvas和javascript动态绘制云朵的好方法?

javascript - 如何将函数作为函数的参数来调用?

javascript - 正则表达式可以匹配字符串开头或结尾的字符(但不能同时匹配两者)吗?

sql - SQL Server 中的动态 SQL

c# - 在 Linq 中使用 .NET 4 动态关键字的好例子?

javascript - 如何在用户控制时禁用 <a onclick>

javascript - if 循环有很多参数 ( 1000 && )