如何处理requireJs超时错误?

时间:2013-08-20 10:30:15

标签: javascript requirejs

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

Uncaught Error: Load timeout for modules: async!http://maps.googleapis.com/maps/api/js?sensor=true

但是我无法捕获此错误并提供替代实现。这是我的gmaps模块定义

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

我该怎么办?

修改

在我的帮助下,我设法找到了可能的解决方案。我已经设置了这样的要求

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

dummymaps只是一个简单的模块:

define({
   dummy: true
});

然后在我的“父母”模块中,我做了:

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

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

编辑2:

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

5 个答案:

答案 0 :(得分:6)

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

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

希望这有帮助!

答案 1 :(得分: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);
});

答案 2 :(得分:2)

我遇到了同样的问题,我用这个片段解决了这个问题:

require(['async!http://maps.google.com/maps/api/js?sensor=false'], function() {
    //Success processing
}, function (e) {
    //Error processing
});

答案 3 :(得分:1)

我相信你原来的问题从来没有完全按照你想要的方式解决,我们在这里遇到了同样的问题。基本上,当谷歌地图超时或不可用时,我们想要一种优雅地恢复的方法,因为有时我们的应用程序将在用户的机器上运行,在那里他们没有互联网访问权限。

我最初使用的是异步!其他人都使用的插件,但无法提供允许我需要的错误处理的修改。

因此,我编写了自己的实用程序类,它在requireJS容器之外异步加载谷歌地图,并提供错误回调处理。看看它是否能解决您的问题。对我们来说,它允许我们在无法访问maps.google.com时为用户呈现一个漂亮的警告视图,并且应用程序的其余部分仍然正常加载:

https://github.com/mag382/googleMapsLoaderUtil

答案 4 :(得分:0)

RequireJS文档有a section on errors,它将涵盖您的特定情况。

如果CDN不可用,请详细说明falling back to a local copy of jQuery

相关问题