如何使用 JavaScript 动态地将脚本插入 HTML 头部?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5132488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:47:23  来源:igfitidea点击:

How can I insert a script into HTML head dynamically using JavaScript?

javascriptdynamic

提问by Wasim A.

How can I insert a script into HTML head dynamically using JavaScript?

如何使用 JavaScript 动态地将脚本插入 HTML 头部?

回答by Bugs Bunny

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onload = function() {
    callFunctionFromScript();
}
script.src = 'path/to/your-script.js';
head.appendChild(script);

回答by Sandesh B Suvarna

document.head.appendChild(document.createElement('script').setAttribute('src','http://ex.com/javascript.js'));

回答by Rajnikant

Here is how I injected a function on the fly without any source file, etc.

这是我在没有任何源文件等的情况下动态注入函数的方法。

document.head.appendChild(document.createElement('script').text = 'function LogIt(msg) { console.log(msg);}' );

And to inject to body

并注射到身体

document.body.appendChild(document.createElement('script').text = 'function LogIt(msg) { console.log(msg);}' );

After executing this, if you try LogIt('hello');, you should see 'hello' in the console.

执行此操作后,如果您尝试LogIt('hello');,您应该在控制台中看到“hello”。