【问题标题】:Dynamically insert script tag? [duplicate]动态插入脚本标签? [复制]
【发布时间】:2019-02-13 02:31:26
【问题描述】:

所以我有这个脚本标签

 <script async="async" data-cfasync="false" src=""></script>

我希望能够动态插入。我试过将它设置为一个变量,

 let scriptTag = '<script async="async" data-cfasync="false" src=""></script>';

并使用 innerHTML 将其添加到我的内容 div 中,但这似乎不起作用。我知道我这样做是非常错误的,我的一部分认为这可能甚至是不可能的。

我想这样做的原因是为了测试目的我可以打开和关闭广告,这样我在测试期间的视图就不会影响分析,这是我应该担心的事情还是可以忽略不计。我只知道在没有打开和关闭广告的测试变量的情况下,我已经被禁止使用 chartboost。

编辑:是的,这与其他问题类似,但没有使用“data-cfasync”等属性来解决。 Mandalina 和 supra28 把它钉在了头上。

【问题讨论】:

标签: javascript html script-tag


【解决方案1】:

您似乎没有正确添加脚本标签。 这是您可以做到的一种方法:

 const script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "";
    script.async = true;
    script.dataset.cfasync = false;  
    document.body.appendChild(script);
    script.addEventListener("load", () => {
      console.log("Script added successfully");
      resolve();
    });

【讨论】:

    【解决方案2】:

    试试这个功能:

    (function () {
        if (typeof window.R === 'undefined') {
            var s = document.createElement('script');
            s.setAttribute('src', 'source goes here!');
            document.body.appendChild(s);  // this appends the script to the body you can also use document.head.appendChild(s) to append to the head
        }
    }());
    

    【讨论】:

      猜你喜欢
      • 2017-01-21
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-12
      • 2022-11-23
      相关资源
      最近更新 更多