javascript - 动态添加的脚本不会执行

标签 javascript script-tag

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

这是我将它添加到页面的方式

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');
});

这是一个活生生的例子

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

最佳答案

因此,我能看到的最佳选择是覆盖(即使只是在脚本加载时暂时覆盖)document.write。这是一种解决方法,但由于您无法控制传入的代码,我认为这可能是您拥有的最好的方法。您也不应该在页面加载后的任何时候使用 document.write,但为了以防万一,我可能会梳理您的代码。

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

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);
});

关于javascript - 动态添加的脚本不会执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7761149/

相关文章:

javascript - phantomjs 使用 src 图像在 canvas.toDataURL 上抛出 DOM 异常 18

javascript - 用图像图案绘制 View

javascript - 由按钮操作的多个任务之一无法执行

javascript - 使用Google protobuf时,如何调用 “System.register()”模块中捕获的javascript函数(由 typescript 生成)?

javascript - vim 使用 tidy 和 Jsbeautifull 自动格式化 html 文件和 &lt;script&gt; 标签

javascript - 单击<th>时如何从标题属性获取文本?

javascript - MIT APP Inventor 打开时出错。如何解决?

javascript - Protractor browser.getCurrentUrl() 不适用于路线更改

javascript - 非 -"text/javascript"类型的 &lt;script&gt; 标签在下载时会阻止 DOMContentLoaded 吗?

javascript - 外部 .js 文件是否需要 &lt;script&gt; 标签?