【问题标题】:Dynamically added script will not execute动态添加的脚本不会执行
【发布时间】:2011-12-07 08:24:28
【问题描述】:

我正在动态添加 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/

【问题讨论】:

    标签: javascript script-tag


    【解决方案1】:

    试试 $(this).append(script) 或 $(this).html(script)

    【讨论】:

    • 我不确定这与我正在做的事情有何不同。 this 只是指#results div。我已经在用基本的 javascript 做这个了。
    【解决方案2】:

    它正在执行,但是由于它使用了document.write,所以它不能工作,只能同步使用。包括async document.write,然后修改你的脚本:

    $('#results').click(function() {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "https://gist.github.com/1265374.js?file=GetGists.js";
        document.write.to = {filename: script.src};
        document.getElementById('results').appendChild(script);
        console.log('script added');
    });
    

    【讨论】:

    • @missingno 我愿意,但我无法控制 github 在他们的嵌入代码中提供的内容。
    • @Eli Grey,我添加了您的代码并将 async document.write 包含到 fiddle,它正在将脚本添加到页面,但它没有执行已添加到页面。
    【解决方案3】:

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

    这里有一个fiddle 有一个可行的解决方案。如果您想在脚本加载后恢复document.write,您可以随时检查script.complete 是否为true,否则,侦听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);
    });
    

    【讨论】:

    • 这种方法似乎在没有任何外部参考的情况下效果最好。
    【解决方案4】:

    因此,作为替代方案,我实际上只是偶然发现了一个似乎可以为您处理此问题的库。查看Injector.js,它应该适合你。

    【讨论】:

      【解决方案5】:

      您的脚本正在执行,您不能从中使用 document.write。使用警报对其进行测试并避免使用 document.write。你的js文件中document.write的语句不会被执行,函数的其余部分会被执行。

      【讨论】:

        【解决方案6】:

        经过数小时的尝试,我能够完成此任务,包括此处的所有其他答案。 我的脚本标签如下所示:

        <script src="https://somedomain.com/some.js"></script>
        

        所以不可能有eval()

        我最后使用了jQuery.getScript(),它获取js文件并执行它:

        var $scriptTag = $('#myElement script');
        var scriptSrc = $scriptTag.attr('src');
        $.getScript(scriptSrc);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-11-23
          • 2015-08-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-26
          • 1970-01-01
          • 2019-01-28
          相关资源
          最近更新 更多