如何处理requireJs超时错误?

san*_*ran 6 javascript requirejs

我正在编写一个使用require.js作为我的加载框架的移动混合应用程序.我有加载错误的问题.我正在尝试做的是在设备离线时设置后备解决方案,我无法下载需要在屏幕上显示地图的google maps API脚本.我得到的只是

Uncaught Error: Load timeout for modules: async!http://maps.googleapis.com/maps/api/js?sensor=true
Run Code Online (Sandbox Code Playgroud)

但我无法捕捉到这个错误,并提供了另一种实现方式.这是我的gmaps模块定义

define('gmaps', ['async!http://maps.googleapis.com/maps/api/js?sensor=true'],function(){
  return window.google.maps;
});
Run Code Online (Sandbox Code Playgroud)

我能做什么?

编辑

由于你的帮助,我设法找到了可能的解决方案.我已经设置了这样的要求

require.config({
    paths: {        
        gmaps: ['http://maps.googleapis.com/maps/api/js?sensor=true', 'lib/dummymaps']
    }
}
Run Code Online (Sandbox Code Playgroud)

dummymaps只是一个简单的模块:

define({
   dummy: true
});
Run Code Online (Sandbox Code Playgroud)

然后在我的"父母"模块中我做:

define(["gmaps"],function(gmaps){
    ...
    if(typeof gmaps.dummy != 'undefined' && gmaps.dummy == true){
        // use a local image as map
    } else {
        // initialize google maps canvas
    }
});
Run Code Online (Sandbox Code Playgroud)

你认为这是一个很好的解决方案吗?

编辑2:

原谅我,它不能使用这段代码.它总是回到替代实现,因为gmaps需要使用异步插件来完全加载,我无法使它与插件一起工作.

anu*_*_29 6

您可以通过以下方式捕获错误:

requirejs.onError = function (err) {
    if (err.requireType === 'timeout') {
        alert("error: "+err);
    } 
    else {
        throw err;
    }   
};
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!


小智 2

您可以尝试以下操作:

requirejs.config({
    paths: {
        // define an alias here, first try remote, if it fails it will try your local file
        'gmaps': ['http://maps.googleapis.com/maps/api/js?sensor=true', 'your local file.js']
    }
});

define('gmaps', function(gm) {
    // var gm should now be the google maps plugin
    console.log(gm);
});
Run Code Online (Sandbox Code Playgroud)