Dan*_*iel 15 javascript jquery asynchronous youtube-api
我正在尝试加载YouTube的iframe API.到目前为止,我所要做的就是制作和加载播放器.它似乎加载了API,但后来没有将"YT.Player()"识别为构造函数.我在chrome js控制台中获得的确切错误是:
Uncaught TypeError: undefined is not a function
Run Code Online (Sandbox Code Playgroud)
那么......世界上我做错了什么?我已经抛出了这个东西的console.log语句,并尝试以几种方式重写它.我已经尝试将api复制到本地文件中.我已经尝试使用常规脚本标记加载它.我尝试使用他们在https://developers.google.com/youtube/iframe_api_reference的API参考中使用的古怪DOM修改加载它.我很确定下面的代码应该有效:
function youtubeAPIReady(script, textStatus, jqXHR)
{
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'CxTtN0dCDaY'
});
}
function readyFunction()
{
$.getScript("https://www.youtube.com/iframe_api", youtubeAPIReady);
}
jQuery(document).ready(readyFunction);
Run Code Online (Sandbox Code Playgroud)
有帮助吗?
Jef*_*ick 14
您可以借用YouTube Direct Lite中使用的技术来推迟加载JavaScript,直到明确需要它为止:
var player = {
playVideo: function(container, videoId) {
if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
window.onYouTubeIframeAPIReady = function() {
player.loadPlayer(container, videoId);
};
$.getScript('//www.youtube.com/iframe_api');
} else {
player.loadPlayer(container, videoId);
}
},
loadPlayer: function(container, videoId) {
new YT.Player(container, {
videoId: videoId,
width: 356,
height: 200,
playerVars: {
autoplay: 1,
controls: 0,
modestbranding: 1,
rel: 0,
showInfo: 0
}
});
}
};
Run Code Online (Sandbox Code Playgroud)
穷人的解决方案,但......
function readyYoutube(){
if((typeof YT !== "undefined") && YT && YT.Player){
player = new YT.Player('player', {
...
});
}else{
setTimeout(readyYoutube, 100);
}
}
Run Code Online (Sandbox Code Playgroud)