yoo yoo - 7 days ago 4
Javascript Question

YT is not defined - Uncaught ReferenceError: [youtube api]

Removed Unwanted Code DEMO

Hey,
I am implementing Youtube Video Player Api and i see some sort of error in console.

any how the video plays perfectly, but i want to know why the error is? if i keep the code outside of Skeleton Patterns, there wont be any error.

can someone please shade some light..

Thanks!!

JS :

(function($) {
$(function(){
var cVid, ytData1;
var callFlexSlider = ({
embedVideos : function(){
function explodeSlider(){
$('.sliderNew .flexslider').flexslider({
slideshow: false
});
$('.sliderNew #carousel, .sliderNew .flex-direction-nav').hide();
}
function explodeShow(){
$('.sliderNew .flexslider').flexslider({
slideshow: true
});
$('.sliderNew #carousel, .sliderNew .flex-direction-nav').show();
}
function getArtistId() {
return window.artist_id;
}
function loadPlayer() {
if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
window.onYouTubePlayerAPIReady = function() {
onYouTubePlayer();
};
}
}
var player;

function onYouTubePlayer() {
player = new YT.Player('player', {
height: '335',
width: '940',
videoId: getArtistId(),
playerVars: {
controls: 1,
showinfo: 0,
rel: 0,
showsearch: 0,
iv_load_policy: 3
},
events: {
'onStateChange': onPlayerStateChange,
'onError': catchError
}
});
}
var done = false;

function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
done = true;
} else if (event.data == YT.PlayerState.ENDED) {
location.reload();
event.target.destroy();
}
}

function onPlayerReady(event) {
console.log('playerReady Event')
}

function catchError(event) {
if (event.data == 100) console.log("...");
}

function stopVideo() {
//alert('asdsad');
//player.destroy();
player.stopVideo();
explodeShow();
}

},
init : function(){
this.embedVideos();
}

});
callFlexSlider.init();
});
})(jQuery);

Answer

Call this loadPlayer(); inside document.ready function and try.

  function loadScript() {
                        if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
                            var tag = document.createElement('script');
                            tag.src = "https://www.youtube.com/iframe_api";
                            var firstScriptTag = document.getElementsByTagName('script')[0];
                            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
                        }
                    }

                    function loadPlayer() {
                            window.onYouTubePlayerAPIReady = function() {
                                onYouTubePlayer();
                            };
                    }


$(function () {
  loadScript();
})