我必须动态加载一些脚本源。由于我不能使用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
更改所有内容以加载它,但我很好奇为什么我的方式不起作用。有没有人有想法?
答案 0 :(得分:1)
可能是因为API.prototype.sourceLoadCnt
不应该存在,它应该是this
上的实例变量。
现在编码它的方式只有在你只有一个实例时才有效,如果你只有一个实例,那么采用oob / prototype方式似乎就是设计失败。