How to insert script into HTML head dynamically using Javascript? [duplicate]

耗尽温柔 提交于 2019-12-29 18:33:09

问题


How to insert script into HTML head dynamically using Javascript ?


回答1:


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



回答2:


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



回答3:


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' on console.



来源:https://stackoverflow.com/questions/5132488/how-to-insert-script-into-html-head-dynamically-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!