问题
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