Search code examples
javascriptsveltegoogle-api-js-clientsvelte-3

GAPI is not defined - Svelte3


I'm having an issue when trying to implement the Youtube data API in my Svelte app. Whenever the site is loaded it just spits the following error: Uncaught ReferenceError: gapi is not defined

The relevant code currently looks as follows:


<svelte:head>
    <script src="https://apis.google.com/js/api.js"></script>
    
</svelte:head>
<script>
    
function start() {
  console.log(GAPIKEY);
  // 2. Initialize the JavaScript client library.
  gapi.client.init({
    'apiKey': GAPIKEY,
  }).then(function() {
    // 3. Initialize and make the API request.
    return gapi.client.request({
      'path': 'https://www.googleapis.com/youtube/v3/playlists',
      'id': 'PLy3-VH7qrUZ5IVq_lISnoccVIYZCMvi-8'
    })
  }).then(function(response) {
    console.log(response.result);
  }, function(reason) {
    console.log('Error: ' + reason.result.error.message);
  });
};

gapi.load('client', start);
</script>

From what I'm able to tell from other similiar Stackoverflow posts this seems to be related to using async and defer in script tags, causing gapi to not be loaded before the code is ran. However since I'm using Svelte, who seems to auto-add them to the compiled code, I am unsure how I am supposed to solve this?

Any help is appreciated!


Solution

  • Add <script src="https://apis.google.com/js/api.js"></script> to your index.html on the public folder instead of loading it on the <svelte:head>