我见过很多与此类似的问题,但我相信这是不同的。当我尝试在全局范围内定义 onYouTubeIframeAPIReady
时,该函数仅在我加载页面的一半时间被调用(如果我不断刷新,有时我会看到控制台消息,有时则不会)那里)。令我感到困惑的是,这种情况有时只会发生,而且我不会在代码的其他任何地方调用 onYouTubeIframeAPIReady
。
我检查过的问题区域:
- 我在 Github Pages 上运行它(所以它不是本地的)
- 函数在全局范围内定义
我的代码如下:
window.onYouTubeIframeAPIReady = function() {
console.log("YouTube API Ready");
player = new YT.Player('player', { // TODO: Sometimes this doesn't work
videoId: curVideoId,
playerVars: {
controls: 1,
autoplay: 0,
disablekb: 1,
enablejsapi: 1,
iv_load_policy: 3,
// modestbranding: 1,
showinfo: 1
}
});
ytLoaded = true;
if (windowWidth) { // if document loaded first
resizePlayer();
}
}
最佳答案
这听起来很可疑,就像您正在通过 DOM 标记中的 src 属性加载 API 库,而不是建议的在页面加载后将其动态添加到 DOM 的方法,或者您正在加载库在创建播放器对象所针对的 DOM 元素之前...因为一旦库加载自身就会调用 onYouTubeIframeAPIReady 函数,所以总是存在这样的可能性,如果您尝试通过标签上的 src 属性加载库它会在您的函数实际注册之前或(在本例中)'player' 元素存在于 DOM 之前加载并调用该函数。工作代码看起来像这样(放置在页面底部附近......绝对低于您试图创建 iframe 的元素):
<div id="player"></div>
<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;
window.onYouTubeIframeAPIReady = function() {
console.log("YouTube API Ready");
player = new YT.Player('player', {
videoId: curVideoId,
playerVars: {
controls: 1,
autoplay: 0,
disablekb: 1,
enablejsapi: 1,
iv_load_policy: 3,
// modestbranding: 1,
showinfo: 1
}
});
ytLoaded = true;
if (windowWidth) { // if document loaded first
resizePlayer();
}
};
</script>
如果我错了,那是您加载库的方式,那么您需要在 Chrome Dev Tools 或 firebug 中进行监控,以查看相关库何时加载当 DOM 元素存在时。
关于javascript - YouTube IFrame API 并不总是加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30986647/