开发者

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

This question already has answers here: How to add DOM element script to head section? 开发者_开发技巧 (13 answers) Closed 5 years ago.

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


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);


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜