4

I tried to load the Google APIs Client Library for JavaScript with requirejs and the async plugin:

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);
});

The usual way to load this library is

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

Everything is loaded in less than 2s but I always get this error:

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 
JJJ
  • 31,545
  • 20
  • 84
  • 99
Sydney
  • 10,908
  • 17
  • 82
  • 129
  • Please where you able to get this working after optimization with r.js (requirejs optimizer)?, For me it works normally but after optimization it doesn't . – I.Tyger Apr 08 '15 at 23:31
  • ^^ Did you manage to fix it after optimization? – jssridhar May 14 '15 at 10:10

1 Answers1

8

TL;DR; change the !callback to !onload that should fix the timeout.

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

The value after the ! is used as the argument name for the async callback, in this case the URI loaded will be something like https://apis.google.com/js/client.js?onload=__async_req_3__ where __async_req_3__ is a global variable (callback function) triggered as soon as the Google API is loaded (notifies the plugin that all dependencies are met).

Miller Medeiros
  • 1,246
  • 14
  • 12
  • You'll likely need to return just `gapi`, as opposed to `gapi.client` – a darren Feb 07 '14 at 13:21
  • 1
    I have tried this and it works if i have not done my build with grunt , but once i build with grunt , it marks the gapi object as undefined . – I.Tyger Apr 08 '15 at 16:20