我正在尝试异步加载 25 个 html 模板
这是我的代码:
        var loopingLoadTemplate = function(index){
            var name = names[index];
            $.get('templates/' + name + '.html', function (data) {
                that.templates[name] = data;
                tplCount++;
                console.log(tplCount + " " + names.length);
                if (tplCount === names.length){
                    callback();
                }
            });
        };
        for (i = 0; i < names.length; i++){
            loopingLoadTemplate(i);
        }
tplCount 是我保留的计数器,因此我知道何时可以安全触发回调
问题是,有 25 个模板要加载,当我在 Chrome 控制台的网络选项卡下检查时,我看到所有 25 个模板都已正确加载,但 console.log 告诉我 tplCount 停止在 21,我不知道为什么. 是因为 for 循环触发得太快以至于 $ 函数的某些回调没有触发吗?
如何安全地异步加载所有这些模板?
所以我也尝试了使用递归调用的同步回退,但它在加载一些模板后神秘地停止并且没有给出警告信号
        var loadTemplate = function (index) {
            var name = names[index];
            console.log("loading " + names[index]);
            $.get('templates/' + name + '.html', function (data) {
                that.templates[name] = data;
                index++;
                if (index < names.length) {
                    loadTemplate(index);
                    console.log("trying another load");
                } else {
                    callback();
                    console.log("trying callback");
                }
            });
        };
        loadTemplate(0);