1
votes

There are multiple YT.player objects created on different elements on the same page.

 player1 = new YT.Player( 'player-1' , {...
 player2 = new YT.Player( 'player-2' , {...
 player3 = new YT.Player( 'player-3' , {...

Some divs visibility is changeable via Javascript. On some browsers (e.g. IE 11) the onPlayerReady callback of the Youtube Iframe API is only called once the DIV becomes visible.

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

Is there some build in check to see wether the YT.player object has been readied or not?

In other words can I check player-1, player-2, player-3 before I call for example stopVideo on them? Because if I call

player-3.stopVideo()

and player-3 has not received an onPlayerReady event, I get an "unknown Method stopVideo()"-Exception.

2

2 Answers

3
votes

I have no perfect solution for that problem. What seems to work is to check if that is a function

if ( typeof player-3.stopVideo === 'function' ) {
    player-3.stopVideo()
}

Best regards,

2
votes

I solved this problem by creating a queue like so:

// Create a queue for anything that needs the YT iFrame API to run
window.YTQueue = {
  hasRun: false,
  queuedItems: [],
  run() {
    this.queuedItems.forEach(item => item());
    this.queuedItems = [];
    this.hasRun = true;
  },
  queueItem(item) {
    this.hasRun ? item() : this.queuedItems.push(item);
  },
};

// Asynchronously load YouTube 'iFrame Player API'
const YouTubeScriptTag = document.createElement('script');
YouTubeScriptTag.src = 'https://www.youtube.com/iframe_api';
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(YouTubeScriptTag, firstScriptTag);

// Called by YouTube API when it's loaded
window.onYouTubeIframeAPIReady() => window.YTQueue.run();

 

Now you can add YouTube iFrame API dependent code to the queue like so:

window.YTQueue.queueItem(() => console.log(window.YT));

 

As you can see from the window.YTQueue.queueItem() method, when you pass a function to it, it will either run it immediately (if the YT API is loaded and ready) or it will queue the passed function until it is.

Hope this helps.