异步加载JavaScript文件与回调 [英] Async Load JavaScript Files with Callback

查看:102
本文介绍了异步加载JavaScript文件与回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个超简单的解决方案来加载一堆JS文件异步。我下面至今下面的脚本。但是回调有时也被称为当脚本实际上并没有加载这会导致错误未找到变量。如果我刷新页面,有时它只是工作,因为我想将文件从缓存直奔,因此在那里比回调快叫,这是很奇怪?

I am trying to write an ultra simple solution to load a bunch of JS files asynchronously. I have the following script below so far. However the callback is sometimes called when the scripts aren't actually loaded which causes a variable not found error. If I refresh the page sometimes it just works because I guess the files are coming straight from the cache and thus are there quicker than the callback is called, it's very strange?

var Loader = function () {

}
Loader.prototype = {
    require: function (scripts, callback) {
        this.loadCount      = 0;
        this.totalRequired  = scripts.length;
        this.callback       = callback;

        for (var i = 0; i < scripts.length; i++) {
            this.writeScript(scripts[i]);
        }
    },
    loaded: function (evt) {
        this.loadCount++;

        if (this.loadCount == this.totalRequired && typeof this.callback == 'function') this.callback.call();
    },
    writeScript: function (src) {
        var self = this;
        var s = document.createElement('script');
        s.type = "text/javascript";
        s.async = true;
        s.src = src;
        s.addEventListener('load', function (e) { self.loaded(e); }, false);
        var head = document.getElementsByTagName('head')[0];
        head.appendChild(s);
    }
}

反正是有测试JS文件被完全加载,没有把一些在实际的JS文件本身,因为我想用同样的方式来加载库在我的掌握(GMaps实现等)。

Is there anyway to test that a JS file is completely loaded, without putting something in the actual JS file itself, because I would like to use the same pattern to load libraries out of my control (GMaps etc).

调用code,就在标记之前。

Invoking code, just before the tag.

var l = new Loader();
l.require([
    "ext2.js",
    "ext1.js"], 
    function() {
        var config = new MSW.Config();
        Refraction.Application().run(MSW.ViewMapper, config);
        console.log('All Scripts Loaded');
    });

感谢您的帮助。

Thanks for any help.

推荐答案

没有什么不对您的code,从我可以告诉,这仅仅是一个Chrome浏览器(它用在window.onload也错误。 )

There is nothing wrong with your code from what I can tell, this is just a bug in Chrome (it does it with window.onload also.)

我想将其添加到被触发的加载功能的作用。如果变量存在,执行JS code,但如果没有,使用的setTimeout在500毫秒左右再次检查。

I'd add it to the function that is triggered in the "load" function. If the variable exists, execute the JS code, but if it doesn't, use a setTimeout to check again in 500ms or so.

这篇关于异步加载JavaScript文件与回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆