我必须动态加载一些脚本源。由于我不能使用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-function只被调用一次。
我仍然可以改变一切,通过XmlHttpRequest加载它,但我很好奇为什么我的方法不起作用。有谁有主意吗?
发布于 2011-01-19 21:11:04
这可能是因为API.prototype.sourceLoadCnt不应该存在,它应该是一个存在于this上的实例变量。
你现在的编码方式只有在你只有一个实例的情况下才会起作用,如果你只有一个实例,走oob/prototype的方式似乎是一个设计上的失败。
https://stackoverflow.com/questions/4735263
复制相似问题