动态添加的脚本将不会执行 [英] Dynamically added script will not execute

查看:105
本文介绍了动态添加的脚本将不会执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

以下是实例

< a href =http://jsfiddle.net/guanome/JqB3g/3/> http://jsfiddle.net/guanome/JqB3g/3/

推荐答案

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

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 using document.write anytime after the page loads, but just in case, I'd maybe comb through your code.

这是一个有效的小提琴 。如果您想在加载脚本后还原 document.write ,您可以随时检查 script.complete 是否为 true ,否则,侦听 onload 事件,该事件应允许您更改文档。写回来。我现在懒得将它编码到小提琴中,但这通常是代码:

Here's a fiddle with a working solution. If you wanted to revert document.write after the script loaded, you can always check to see if script.complete is true, otherwise, listen for an onload event, which should allow you to change document.write back. I'm too lazy to code it into the fiddle at the moment, but this would be the code generally:

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

这篇关于动态添加的脚本将不会执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆