Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
Youtube Iframe API Svelte document.create error

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!