javascript / youtube api - variable YT is not defined

后端 未结 2 1345
醉话见心
醉话见心 2020-12-15 12:28

I\'m creating a youtube player embed via the YT api but I keep getting an alert that the variable YT is not defined. I can see that the script for the youtube API is getting

2条回答
  •  遥遥无期
    2020-12-15 13:14

    You'll need to wrap the YT call in a function and call it when the script is included. Or you can add the script from the file instead of calling that script to include another script.

    function doYT(){
        window.player = new YT.Player('video_player', {
            width: '768',
            height: '432',
            videoId: vidID,
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        }
    }
    
    window.YT && doYT() || function(){
        var a=document.createElement("script");
        a.setAttribute("type","text/javascript");
        a.setAttribute("src","http://www.youtube.com/player_api");
        a.onload=doYT;
        a.onreadystatechange=function(){
            if (this.readyState=="complete"||this.readyState=="loaded") doYT()
        };
        (document.getElementsByTagName("head")[0]||document.documentElement).appendChild(a)
    }();
    

提交回复
热议问题