Dynamically add script tag with src that may include document.write

Cadell Christo picture Cadell Christo · Oct 29, 2012 · Viewed 255.8k times · Source

I want to dynamically include a script tag in a webpage however I have no control of it's src so src="source.js" may look like this.

document.write('<script type="text/javascript">')
document.write('alert("hello world")')
document.write('</script>')
document.write('<p>goodbye world</p>')

Now ordinarily putting

<script type="text/javascript" src="source.js"></script> 

in the head works fine but is there any other way I can add source.js dynamically using something like innerHTML?

jsfiddle of what i've tried

Answer

dmp picture dmp · Oct 29, 2012
var my_awesome_script = document.createElement('script');

my_awesome_script.setAttribute('src','http://example.com/site.js');

document.head.appendChild(my_awesome_script);