"Cannot read property 'load' of undefined"

Bennett picture Bennett · May 27, 2017 · Viewed 21.6k times · Source

I'm attempting to follow this documentation to integrate with Google sign in, though I'm running into this error in console:

Uncaught TypeError: Cannot read property 'load' of undefined
        at script.js:1

script.js:

window.gapi.load('auth2', function() {
    console.log('Loaded!');
});

I get the error about half of the time, and inspecting the network panel in Chrome, it only happens when the following resource is not loaded:

https://apis.google.com/_/scs/apps-static/_/js/k=oz.gapi.en.d2dliHDvPwE.O/m=auth2/exm=signin2/rt=j/sv=1/d=1/ed=1/am=AQ/rs=AGLTcCNGAKhVlpzmTUpjFgzBXLpLM_oEFg/cb=gapi.loaded_1

How can I eliminate this error?

If it's useful, here's my index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Google Sign In Test</title>
        <meta name="google-signin-client_id" content="*****.apps.googleusercontent.com">
        <script src="https://apis.google.com/js/platform.js" async defer></script>
        <script src="script.js" async defer></script>
    </head>
    <body>
        <div class="g-signin2" data-onsuccess="onSignIn"></div>
    </body>
</html>

Answer

thewolff picture thewolff · May 27, 2017

Try adding an onload event to the script tag. So change your script tag to

<script src="https://apis.google.com/js/platform.js?onload=myFunc" async defer></script>

Then wrap your code in the callback function.