I am dynamically adding a script of a github gist. If I added it to the html before the page loads, the script will execute. But If I try to add it to the page after it loads it adds the script to the page but doesn't execute it.
Here is how I am adding it to the page
Html
<div id="results"></div>
Javascript
$('#results').click(function() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://gist.github.com/1265374.js?file=GetGists.js";
document.getElementById('results').appendChild(script);
console.log('script added');
});
Here is the live example
So, the best option I can see is to override (even if just temporarily while the script loads)
document.write. It is sort of a work around, but since you don't control the code coming in, I think it may be the best you've got. You also shouldn't be usingdocument.writeanytime after the page loads, but just in case, I'd maybe comb through your code.Here's a fiddle with a working solution. If you wanted to revert
document.writeafter the script loaded, you can always check to see ifscript.completeistrue, otherwise, listen for anonloadevent, which should allow you to changedocument.writeback. I'm too lazy to code it into the fiddle at the moment, but this would be the code generally: