I am trying to use Youtube videos using Youtube Iframe API in my Svelte application. I get a variable is. not defined error. Here is my code
<script context="module">
import { onMount } from 'svelte';
// 2. This code loads the IFrame Player API code asynchronously.
onMount(() => {
var tag = document.createElement('script');
});
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
window.onYouTubeIframeAPIReady = function () {
console.log('hello')
}
</script>
<script>
export let videoId
</script>
<div>
YT-Component VID: {videoId}
</div>
My error is: tag is not defined ReferenceError: tag is not defined at Youtube.svelte:10:4 at async instantiateModule (/Users/emrahgunel/Desktop/NAZ-BRAND-MichelobUltra/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:50286:9)
How can I fix this error. Thanks
tag is scoped to onMount, you should move your other code that interacts with it there as well.
Also, you usually should not use functions like document.getElementsByTagName because they create unnecessary dependencies on structure. Generally, bind:this is used to get access to specific elements within a component.
In the case of adding scripts, you can just append them to document.body.
Assigning window.onYouTubeIframeAPIReady will cause issues when you have more instances of the component as this overwrites any existing event handler.