[英]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/
我想念什么嗎?
我找到了解決辦法,
首先,您無法通過外部加載的腳本編寫任何內容來編寫文檔,
無法對“文檔”執行“寫入”:除非已明確打開,否則無法從異步加載的外部腳本寫入文檔
有兩種解決方法。
1)。
您正在將iframe創建為html內容,並以
document.write(htmlCode)
上面一行創建問題,用於動態加載您的內容。
而不是您的代碼嘗試以下類似。
var htmlCode = document.createElement("iframe");
htmlCode.setAttribute("title", title.replace(/[\\"']/g,'\\$&').replace(/&/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
讓我知道您是否仍然遇到任何問題。
嘗試使用
window.onload = function() {
//your script declaration here
}
而不是jquery ready()
您可以使用jQuerys getScript()加載和執行腳本。 它不需要位於DOM中就可以訪問元素。
$.getScript ("test.js", function (){
alert ("Running test.js");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.