[英]load text dynamically in javascript using createElement('link')
[英]Dynamically load additional Javascript source files with createElement();
我必須動態加載一些腳本源。 由於我無法使用jQuery並且不了解XmlHttpRequest
+ eval
方法,因此我嘗試通過以下方式進行操作:
API.prototype.initCallback = null;
API.prototype.sourceLoadCnt = 0;
API.prototype.sourceReady = function () {
this.sourceLoadCnt--;
if(this.sourceLoadCnt===0){
this.initCallback(); //if all sources loaded
}
}
API.prototype.init = function (callback) {
this.initCallback = callback;
var _this = this;
var js = "../../js/";
var script1 = document.createElement('script');
script1.type = 'text/javascript';
script1.src = js+'script1.js';
this.sourceLoadCnt++;
script1.onload = function(){ _this.sourceReady() };
var script2 = document.createElement('script');
script2.type = 'text/javascript';
script2.src = js+'script2.js';
this.sourceLoadCnt++;
script2.onload = function(){ _this.sourceReady() };
var css1 = document.createElement('link');
css1.type = 'text/css';
css1.rel = 'stylesheet';
css1.href = 'style.css';
css1.media = 'screen';
this.sourceLoadCnt++;
css1.onload = function(){ _this.sourceReady() };
head.appendChild(script1);
head.appendChild(script2);
head.appendChild(css1);
};
我的問題是, sourceReady
僅被調用一次。
我仍然可以更改所有內容以通過XmlHttpRequest
加載它,但是我很好奇為什么我的方法行不通。 有人有主意嗎?
可能是因為API.prototype.sourceLoadCnt
不應該存在,它應該是API.prototype.sourceLoadCnt
在this
上的實例變量。
現在,您的編碼方式僅在只有一個實例的情況下才有效,並且如果只有一個實例,則使用oob / prototype方法似乎是設計失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.