首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用createElement()动态加载额外的Javascript源文件;

问使用createElement()动态加载额外的Javascript源文件;
EN

Stack Overflow用户
提问于 2011-01-19 20:32:33
回答 1查看 608关注 0票数 0

我必须动态加载一些脚本源。由于我不能使用jQuery,也不知道XmlHttpRequest+eval方法,所以我尝试这样做:

代码语言:javascript
复制
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加载它,但我很好奇为什么我的方法不起作用。有谁有主意吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-01-19 21:11:04

这可能是因为API.prototype.sourceLoadCnt不应该存在,它应该是一个存在于this上的实例变量。

你现在的编码方式只有在你只有一个实例的情况下才会起作用,如果你只有一个实例,走oob/prototype的方式似乎是一个设计上的失败。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4735263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档