Search code examples
javascriptgoogle-oauth

Google platform.js sometimes not firing onload callback


The following will not call platform_callback if I load other javascript sources in a particular order.

<script type="text/javascript" src="//apis.google.com/js/platform.js?onload=platform_callback" async defer></script> 
<script>
    function platform_callback() {
        console.log("callback");
    }
</script>

I'm having a difficult time replicating this... but if I have a lot of js libraries (angular, moment, bootstrap) loading after platform is called, the onload callback is not firing.

Here is a gif showing that the console.log is only firing some of the time after refreshing about a dozen times: https://i.imgur.com/C5FFJhb.gif

This html causes the issue:

<script src="https://apis.google.com/js/platform.js?onload=platform_callback" async defer></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular-animate.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular-route.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular-sanitize.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js" crossorigin="anonymous"></script>
<script>
    function platform_callback() {
        console.log("init");
        gapi.load('auth2', function() {
            console.log("auth2");
        });
    }
</script>

Solution

  • The google library is loaded then calls platform_callback which may not be defined at that time if the browser is busy loading the other js files.