I have a web page that uses the YouTube Player API. I am not having the problem of onYouTubeIframeAPIReady() never being called. It definitely is called. Instead, when that function is called, the YouTube API is not fully loaded. This leads to the constructor exception "yt.player is not a constructor" when I try to create the player instance in that method, because YT.Player has not been defined yet. If I check the status of the YT object, I see that it does exist but it's top level properties show these values:
{loading: 1, loaded: 0, ready: ƒ, setConfig: ƒ}
As you can see the loading field is still TRUE (equal to 1) and the loaded field is still FALSE (equal to 0).
Out of desperation I changed my code from below:
function onYouTubeIframeAPIReady()
{
console.log("onYouTubeIframeAPIReady() called.");
player = new YT.Player('player',
{
height: '390',
width: '640',
videoId: "i8MOJho5TDs"
events:
{
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
} // function onYouTubeIframeAPIReady()
To a version that uses an Interval to poll the loaded field for a TRUE (equal to 1) value. If it is not TRUE then a new interval is set to try again 100 milliseconds later, using this code:
function createYouTubePlayer()
{
if (!YT.loaded)
{
console.log('YouTube Player API is still loading. Retrying...');
setInterval(createYouTubePlayer, 100);
return;
} // if (!YT.loaded)
console.log('YouTube Player API is loaded. Creating player instance now.');
player = new YT.Player('player',
{
height: '390',
width: '640',
videoId: "i8MOJho5TDs", // 'M7lc1UVf-VE',
events:
{
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onYouTubeIframeAPIReady()
{
console.log("onYouTubeIframeAPIReady() called.");
setInterval(createYouTubePlayer, 100);
} // function onYouTubeIframeAPIReady()
Here is the function that loads the YouTube API. It is called from a script tag in the HEAD section of the HTML document:
// This function initialize the YouTube IFrame Player API.
function initializeYouTubePlayerAPI()
{
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
console.log("YouTube Player API load initiated.");
}
Unfortunately, this approach doesn't help because the loaded property of the YouTube API YT object never changes to TRUE (equal to 1). Therefore I see a stream of console messages showing the endless retries while the code waits for the YouTube Player API to fully load.
Does anyone now why this is happening or how I can fix it?
Note, I did try this operation from incognito mode in Chrome in case the problem was due to interference from a Chrome extension. That didn't help so I don't think that's the problem.