如何检查是否YT.播放器对象已经准备好了



有多个YT。在同一页面的不同元素上创建播放器对象。

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

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

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

是否有一些内置检查,看看是否YT。播放器对象是否已经准备好了?

换句话说,我可以在调用stopVideo之前检查player1, player2, player3吗?因为如果我调用

player-3.stopVideo()

和player-3没有收到一个onPlayerReady事件,我得到一个"未知方法stopVideo()"-异常

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

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

问好,

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

// 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已加载并准备好),或者将传递的函数排队,直到它完成。

最新更新