在同一页面上的不同元素上创建了多个YT.player对象。
player1 = new YT.Player( 'player-1' , {...
player2 = new YT.Player( 'player-2' , {...
player3 = new YT.Player( 'player-3' , {...一些div的可见性可以通过Javascript改变。在某些浏览器(例如IE11)上,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.player对象是否已经准备好了?
换句话说,我可以在调用stopVideo之前检查player-1,player-2,player-3吗?因为如果我打电话给
player-3.stopVideo()并且player-3还没有收到onPlayerReady事件,我得到了一个“未知方法stopVideo()"-Exception。
发布于 2014-05-13 20:02:07
对于这个问题,我没有完美的解决方案。有效的方法似乎是检查这是否是一个函数
if ( typeof player-3.stopVideo === 'function' ) {
player-3.stopVideo()
}诚挚的问候,
发布于 2018-12-03 23:59:01
我通过创建如下队列解决了这个问题:
// 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已加载并准备就绪),要么将传递的函数排入队列,直到该函数加载就绪。
希望这能有所帮助。
https://stackoverflow.com/questions/23613442
复制相似问题