使用requirejs timeout加载异步资源

时间:2013-08-05 21:02:02

标签: javascript requirejs

我尝试使用requirejs和async插件加载适用于JavaScript的Google API客户端库:

require.config({
    paths : {
        async : '../lib/requirejs/async'
    },
    waitSeconds: 60
});

define('gapi', ['async!https://apis.google.com/js/client.js!callback'],
    function(){
        console.log('gapi loaded');
        return gapi.client;
    }
);

require(['gapi'], function(){
    console.log("Callback");
    console.log(gapi);
});

load this library的常用方法是

<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>

所有内容都在不到2秒内加载但我总是收到此错误:

Uncaught Error: Load timeout for modules: async!https://apis.google.com/js/client.js!callback_unnormalized2,async!https://apis.google.com/js/client.js!callback
http://requirejs.org/docs/errors.html#timeout 

1 个答案:

答案 0 :(得分:8)

TL; DR; !callback更改为应修复超时的!onload

define('gapi', ['async!https://apis.google.com/js/client.js!onload'],
    function(){
        console.log('gapi loaded');
        return gapi.client;
    }
);

!之后的值用作异步回调的参数名称,在这种情况下,加载的URI将类似https://apis.google.com/js/client.js?onload=__async_req_3__,其中__async_req_3__是全局变量(回调)功能)在加载Google API后立即触发(通知插件已满足所有依赖项)。