如何检查YT.Player对象是否已准备就绪?

时间:2014-05-12 15:48:02

标签: javascript youtube youtube-api youtube-javascript-api

在同一页面上的不同元素上创建了多个YT.player对象。

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

一些div的可见性可以通过Javascript改变。在某些浏览器(例如IE 11)上,只有在DIV变为可见时才会调用Youtube Iframe API的onPlayerReady回调。

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

是否有一些内置检查以确定YT.player对象是否已准备就绪?

换句话说,在我打电话给stopVideo之前,我可以查看播放器-1,播放器-2,播放器-3吗?因为如果我打电话

player-3.stopVideo()

并且播放器3没有收到onPlayerReady事件,我得到一个“未知方法stopVideo()” - 例外。

2 个答案:

答案 0 :(得分:3)

我对这个问题没有完美的解决方案。似乎有用的是检查这是否是一个函数

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

致以最诚挚的问候,

答案 1 :(得分:0)

我通过创建一个队列来解决了这个问题:

// 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();

现在您可以将YouTube iFrame API依赖的代码添加到队列中,如下所示:

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

window.YTQueue.queueItem()方法中可以看到,将函数传递给函数时,它将立即运行(如果YT API已加载并准备就绪),或者将传递的函数排队直到它被

希望这会有所帮助。