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

查看:23
本文介绍了使用回调异步加载 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 文件本身中放入任何内容,因为我想使用相同的模式来加载不受我控制的库(GMap 等).

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).

调用代码,就在标签之前.

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');
    });

感谢您的帮助.

推荐答案

据我所知,您的代码没有任何问题,这只是 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代码,如果不存在,则使用setTimeout在500ms左右再次检查.

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天全站免登陆