How to wait for a library to be loaded before routing

92 views
Skip to first unread message

Renaud T

unread,
Sep 20, 2015, 2:55:07 PM9/20/15
to Sammy.js

Hello all, I am currently building a Single Page App based on Google Cloud Endpoints (REST Api) which uses Sammy.js for routing.


Introduction


To be able to use Endpoints I need to load a Google javascript Library, by adding the following script tag at the end of the HTML page:


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


And In the "init" callback function, I have to load my Endpoint. Pls see https://cloud.google.com/appengine/docs/java/endpoints/consume_js for more details.


I have a Sammy route which displays a list of items coming from the Endpoint, through:

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


My problem


When I call this route from a button (or menu item) in the page, there is no problem, since the Google javascript Library is already loaded, as well as the Endpoint.

However, when I call this route directly via the browser's address bar, I get a 500 Error because the javascript Library didn't have time to load before the routing is triggered.


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

I found a solution by waiting the library (and the Endpoint) to be loaded before calling the Endpoint with the code below. But I don't find that very elegant and there are probably some better/more efficient ways to handle this problem.


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

Any suggestion would be very welcome, thanks in advance!


FYI, I've posted the same question on SO: http://stackoverflow.com/questions/32682147

Andriy Zhdanov

unread,
Sep 21, 2015, 4:00:34 AM9/21/15
to Sammy.js
Hi Renaud,

Try invoking Sammy.run() only when all your apis are loaded. E.g.

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

Renaud T

unread,
Sep 21, 2015, 1:39:00 PM9/21/15
to Sammy.js
Many thanks Andriv, it work very well!

Just note that the Sammy.run() has to be called as a a callback function of the of Endpoint loading, like:

       function init() {
           
var ROOT = 'https://yourendpoint.appspot.com/_ah/api';
            gapi
.client.load(
                   
'myEndpointApi',
                   
'v1',
                   
function() {
                        app
.run();
                   
},
                    ROOT
);
       
}

Renaud T

unread,
Sep 21, 2015, 1:40:48 PM9/21/15
to Sammy.js
I mean Andriy, sorry :-)
Reply all
Reply to author
Forward
0 new messages