YouTube IFrame API doesn't always load?

北战南征 提交于 2019-12-06 03:15:13

This sounds suspiciously like you're loading the API library via a src attribute on a in your DOM tag rather than the suggested way of dynamically adding it to the DOM after the page has loaded, or that you're loading the library before the DOM element that the player object is targeting has been created ... because the onYouTubeIframeAPIReady function is called as soon as the library loads itself, the possibility always exists that, if you try loading the library via a src attribute on a tag that it'll load and call the function before your function is actually registered or before the (in this case) 'player' element exists in the DOM. Working code would look something like this (placed near the bottom of your page ... definitely below the element you're trying to create the iframe in place of):

<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>

If I'm wrong, and that is how you're loading the library, then you'll want to monitor in Chrome Dev Tools or firebug to see when the library is getting loaded in relation to when the DOM element exists.

You forgot your semicolon at the end:

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();
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!