javascriptttt
javascriptttt

Reputation: 730

Non-dynamic insertion of youtube player iframe doesn't fire events

I'm using youtube's iframe api

https://developers.google.com/youtube/iframe_api_reference#Loading_a_Video_Player

I want to write the <iframe> tag by hand (not insert it asynchronously). The docs suggest this is possible

If you do write the tag, then when you construct the YT.Player object, you do not need to specify values for the width and height, which are specified as attributes of the tag(...)

But when I insert the <iframe> tag directly

  <iframe id="player" type="text/html" width="640" height="390"
  src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com"
  frameborder="0"></iframe>

and remove the dynamic tag generation

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

(and width, height and id from the options when creating a new player instance)

I cannot get the function onYouTubeIframeAPIReady to be called. I've tried using the dynamic insertion of the script tag and it works. The docs are a bit unclear about what's needed for when you don't dynamically inserted - so I'd be grateful for advice

Thanks

Upvotes: 1

Views: 369

Answers (1)

jlmcdonald
jlmcdonald

Reputation: 13667

When you have your iframe element already present on the page, you still have to load the iframe javascript library, as it's that library which calls onYouTubeIFrameAPIReady. So your code should look something like this:

<iframe id="player" type="text/html" width="640" height="390"
  src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com"
  frameborder="0"></iframe>

<script>
      var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }
</script>

Note that in this case, the value you pass to onYouTubeIFrameAPIReady is the ID of your iframe, rather than the ID of a div ... the library will recognize this is an iframe and hook into the existing video rather than trying to dynamically generate an iframe for you.

Upvotes: 1

Related Questions