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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, thank you. I guess I will do it the other way described here: stackoverflow.com/questions/3523091/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.