我见过很多类似的问题,但我相信这是不同的。当我尝试定义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 属性加载库,它会在您的函数实际注册之前或在 DOM 中存在(在本例中)“player”元素之前加载并调用该函数。工作代码看起来像这样(放置在页面底部附近......绝对位于您尝试创建 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>
如果我错了,那is如何加载库,那么您需要在 Chrome 开发工具或 firebug 中进行监视,以查看库何时加载以及 DOM 元素何时存在。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)