动态添加的脚本将不会执行

gua*_*ome 9 javascript script-tag

我正在动态添加github gist的脚本.如果我在页面加载之前将其添加到html,脚本将执行.但是如果我在加载后尝试将其添加到页面,它会将脚本添加到页面但不执行它.

以下是我将其添加到页面的方式

HTML

<div id="results"></div>
Run Code Online (Sandbox Code Playgroud)

使用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');
});
Run Code Online (Sandbox Code Playgroud)

这是现场的例子

http://jsfiddle.net/guanome/JqB3g/3/

Lov*_*ing 9

所以,我能看到的最佳选择是覆盖(即使在脚本加载时暂时只是)document.write.这是一种解决方法,但由于你不控制进入的代码,我认为它可能是你得到的最好的.您也不应该document.write在页面加载后随时使用,但为了以防万一,我可能会梳理您的代码.

这是一个工作解决方案的小提琴.如果你想document.write在加载脚本后恢复,你可以随时检查是否script.completetrue,否则,监听一个onload事件,这应该允许你改document.write回来.我现在懒得将它编码到小提琴中,但这通常是代码:

script.src = "...";
document.getElementById("results").appendChild(script);
if(script.complete) document.write = document._write;
else script.load(function() { 
    // Goes to the end of the run queue so that the script 
    // is guaranteed to run before this code
    setTimeout(function(){document.write = document._write;},0);
});
Run Code Online (Sandbox Code Playgroud)