在javascript文件中动态包含javascript代码

Dynamically include javascript code from within javascript file

本文关键字:javascript 包含 代码 动态 文件      更新时间:2023-09-26

我正在将以下脚本插入到第三方的外部页面中,该脚本位于我自己的服务器上: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>

这是我想要动态注入的另一个脚本,请注意,它不能只是添加到上面的脚本中!我希望这个脚本是动态可用的。此完整代码稍后将存储在对象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 to execute '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();