2011-01-19 43 views
0

我必須動態加載一些腳本源代碼。既然不能使用jQuery和不知道的XmlHttpRequest + eval方法,我試圖做這樣說:用createElement()動態加載其他Javascript源文件;

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加載它,但我很好奇爲什麼我的方式不工作。有人有想法嗎?

回答

1

這可能是因爲API.prototype.sourceLoadCnt不應該存在,它應該是一個實例變量,它位於this上。

你現在編碼的方式只有在你只有一個實例時纔有效,如果你只有一個實例,那麼使用oob/prototype原型就好像是一個設計失敗。

+0

好的,謝謝。我想我會做到這裏描述的另一種方式:http://stackoverflow.com/questions/3523091/dynamically-loading-javascript-files-and-load-completion-events – Simon 2011-01-19 14:50:31