使用 jQuery 动态添加时脚本未加载

Script not loading when added dynamically with jQuery

我正在尝试使用 jQuery 将脚本动态添加到我的项目中。脚本已成功添加到 head 标签,但内容未呈现在 body 标签中。

这是我的代码:

  <script type="text/javascript">
    window.onload = function() {
        var s = document.createElement("script");
        s.type = "text/javascript";
        s.src = "https://form.jotform.com/jsform/81003857231348";
        $("head").append(s);
    }
  </script>

但是,如果我直接添加,脚本会成功加载:
<script type="text/javascript" src="https://form.jotform.com/jsform/81003857231348"></script>

https://jsfiddle.net/xpvt214o/98587/

我是不是漏掉了什么?

尝试使用

window.onload = function() {
   //your script declaration here
}

而不是jquery ready()

您可以使用 jQuerys getScript() 加载和执行脚本。它不需要在 DOM 中就可以访问您的元素。

$.getScript ("test.js", function (){

    alert ("Running test.js");

});

我找到了解决方案,

首先,您不能从外部加载的脚本向文档写入任何内容,

无法在 'Document' 上执行 'write': 除非显式打开

,否则无法从 asynchronously-loaded 外部脚本写入文档

有两种方法可以解决这个问题。

1).

您正在创建 Iframe 作为 html 内容并写入文档作为

document.write(htmlCode)

上面一行创建了动态加载您的内容的问题。

请尝试下面的代码,而不是您的代码。

var htmlCode = document.createElement("iframe");
 htmlCode.setAttribute("title", title.replace(/[\"']/g,'\$&').replace(/&amp;/g,'&'));
 htmlCode.setAttribute("src","");
 htmlCode.setAttribute("allowtransparency","true");
 htmlCode.setAttribute("allow","geolocation; microphone; camera");
 htmlCode.setAttribute("allowfullscreen","true");
 htmlCode.setAttribute("name",this.formId);
 htmlCode.setAttribute("id",this.iframeDomId);

 document.body.appendChild(htmlCode);

并在你的html

中添加如下Js代码
<script type="text/javascript">
   var s = document.createElement("script");
   s.type = "text/javascript";
    s.src = "https://form.jotform.com/jsform/81003857231348";
   document.getElementsByTagName("head")[0].appendChild(s);
</script>

2).

而不是

document.write(htmlCode)

尝试

document.body.innerHTML=htmlCode

如果您仍然遇到任何问题,请告诉我。