简体   繁体   English

使用createElement()动态加载其他Javascript源文件;

[英]Dynamically load additional Javascript source files with createElement();

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: 由于我无法使用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);
};

My problem is, that the sourceReady -function is called only once. 我的问题是, sourceReady仅被调用一次。

I still could change everything to load it via XmlHttpRequest but I am curious why my way isn't working. 我仍然可以更改所有内容以通过XmlHttpRequest加载它,但是我很好奇为什么我的方法行不通。 Does anyone have an idea? 有人有主意吗?

It might be because API.prototype.sourceLoadCnt should not exist, it should be an instance variable that lives on this . 可能是因为API.prototype.sourceLoadCnt不应该存在,它应该是API.prototype.sourceLoadCntthis上的实例变量。

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. 现在,您的编码方式仅在只有一个实例的情况下才有效,并且如果只有一个实例,则使用oob / prototype方法似乎是设计失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM