[英]how to tell when script added by document.createElement('script') is loaded
我在加載頁面后根據如下條件加載腳本:
function isScriptAlreadyIncluded(src){
var scripts = document.getElementsByTagName("script");
for(var i = 0; i < scripts.length; i++){
if(scripts[i].getAttribute('src') === src) return true;
else return false;
}
}
if(isScriptAlreadyIncluded('contextualConversation.js')) contextualReplace();
else{
var cCScript = document.createElement('script');
cCScript.src = 'contextualConversation.js';
contextualReplace();
}
我的問題是,在腳本加載之前,else中的contextualReplace()
正在執行。 那么,如何在剛添加的腳本加載完成后告訴它運行該功能?
您可以嘗試以下方法:
html文件
<script>
function onScriptLoad()
{
alert('script loaded');
}
//your logic to append script tag
</script>
js文件加載
//your other script
(function()
{
onScriptLoad(); //<-- invoke here
})();
除了版本9之前的IE之外,腳本都會觸發事件onload-
else{
var cCScript = document.createElement('script');
cCScript.onload=contextualReplace;
cCScript.src = 'contextualConversation.js';
}
(要覆蓋較舊的IE,可以使用它的readystatechange事件,請檢查Microsoft開發人員網絡)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.