I'm trying to load YouTube's iframe API. So far, all I'm trying to do is make and load the player. It seems to load the API, but then not recognize "YT.Player()" as a constructor. The exact error I'm getting at that line, in the chrome js console, is:
Uncaught TypeError: undefined is not a function
So... What in the world am I doing wrong? I've thrown console.log statements all over this thing, and tried rewriting it in a few ways. I've tried copying the api into a local file. I've tried loading it with regular script tags. I've tried loading it with the wacky DOM Modification they used in the api reference at https://developers.google.com/youtube/iframe_api_reference. I'm pretty sure the code below should work:
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);
Any help?
You can borrow the technique used in YouTube Direct Lite to defer loading the JavaScript until it's explicitly needed:
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
}
});
}
};
poor man's solution, but ...
function readyYoutube(){
if((typeof YT !== "undefined") && YT && YT.Player){
player = new YT.Player('player', {
...
});
}else{
setTimeout(readyYoutube, 100);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With