javascript / youtube api - variable YT is not defined

喜你入骨 提交于 2019-11-29 00:03:02

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)
}();

This is the method I like best. Uses jQuery FYI.

var player = {
    playVideo: function(container, videoId) {
        if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
            window.onYouTubePlayerAPIReady = function() {
                player.loadPlayer(container, videoId);
            };
            $.getScript('//www.youtube.com/player_api');
        } else {
            player.loadPlayer(container, videoId);
        }
    },
    loadPlayer: function(container, videoId) {
        window.myPlayer = new YT.Player(container, {
            playerVars: {
                modestbranding: 1,
                rel: 0,
                showinfo: 0,
                autoplay: 1
            },
            height: 200,
            width: 200,
            videoId: videoId,
            events: {
                'onStateChange': onPlayerStateChange
            }
        });
    }
};

var containerId = 'ytplayer';
var videoId = 'abc123';
player.playVideo(containerId, videoId);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!