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

Was*_* A. 37 javascript dynamic

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

Bug*_*nny 53

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);
Run Code Online (Sandbox Code Playgroud)

  • 应该有一个解释。 (3认同)

RAJ*_*RAJ 6

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

document.head.appendChild(document.createElement('script').text = 'function LogIt(msg) { console.log(msg);}' );
Run Code Online (Sandbox Code Playgroud)

并注射到体内

document.body.appendChild(document.createElement('script').text = 'function LogIt(msg) { console.log(msg);}' );
Run Code Online (Sandbox Code Playgroud)

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