0

I have to load some script source dynamically. Since I can not use jQuery and did not know about the XmlHttpRequest+eval method, I tried to do it this way:

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);
};

My problem is, that the sourceReady-function is called only once.

I still could change everything to load it via XmlHttpRequest but I am curious why my way isn't working. Does anyone have an idea?

Simon
  • 4,395
  • 8
  • 33
  • 50

1 Answers1

1

It might be because API.prototype.sourceLoadCnt should not exist, it should be an instance variable that lives on this.

The way you have coded it now will only work if you only have a single instance, and if you only have a single instance, going the oob/prototype way seems like a design failure.

Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68
  • Ok, thank you. I guess I will do it the other way described here: http://stackoverflow.com/questions/3523091/dynamically-loading-javascript-files-and-load-completion-events – Simon Jan 19 '11 at 14:50