It's not enough to simply set the innerHTML to something that contains a script tag. You must create a script element and append it to the DOM. I believe the intent is to give some cross site scripting protection when injecting massive blobs of content.
var script = document.createElement('script');
script.innerHTML = "alert('ran some JS');";
document.body.appendChild(script);
Example: http://jsfiddle.net/axvaT/
document.write
won't work like you think though. document.write
will not place text where the script tag is. Instead it will place text where the HTML parser is currently looking at. Depending on when the JS code is run, these may be the same, or maybe entirely different.
So for this reason, among others, never use document.write
for anything. Ever. Even debugging.
Lastly, while sometimes it's useful to inject a script tag pointing to some other js file:
var script = document.createElement('script');
script.src = 'somefile.js';
document.head.appendChild(script);
Doing this with a script tag that has JS in it makes no sense. You are using javascript to create a script tag that should immediately run some javascript. Why not just run that javascript that you want to run away instead of creating a new script tag to do it for you?
So don't do:
var script = document.createElement('script');
script.innerHTML = "alert('ran some JS');";
document.body.appendChild(script);
Instead just do:
alert('ran some JS');