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