Sammy.js 路由:如何在路由之前等待库加载

Sammy.js routing: How to wait for a library to be loaded before routing

我目前正在构建一个基于 Google Cloud Endpoints (REST Api) 的单页应用程序,它使用 Sammy.js 进行路由。

简介

为了能够使用端点,我需要加载一个 Google javascript 库,方法是在 HTML 页面末尾添加以下脚本标记:

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

并且在 "init" 回调函数中,我必须加载我的端点。请参阅https://cloud.google.com/appengine/docs/java/endpoints/consume_js了解更多详情。

我有一条 Sammy 路线,它显示来自端点的项目列表,通过:

this.get('#/listAllItems', function () {
   listItems();  // function which calls the Endpoint and displays the results
});

问题

当我从页面中的按钮(或菜单项)调用此路由时,没有问题,因为 Google javascript 库以及端点已经加载。

但是,当我直接通过浏览器的地址栏调用此路由时,出现 500 错误,因为 javascript 库在路由被触发之前没有时间加载。

body 500 Error get /page.html#/listAllItems gapi.client is undefined

我找到了一个解决方案,方法是在使用下面的代码调用端点之前等待库(和端点)加载。但我觉得这不是很优雅,可能有一些 better/more 有效的方法来处理这个问题。

this.get('#/listAllItems', function () {
  function checkGapi() {
    if ((gapi.client) && (gapi.client.myEndpointApi)) {
      listItems();
    } else {
      window.setTimeout(checkGapi, 50);
    }
  }
  checkGapi();
});

非常欢迎任何建议,在此先感谢!

在加载所有 api 时调用 Sammy.run() 应该可以解决问题。例如

var app = Sammy(...);
function init() {
   app.run();
}