jribeiro jribeiro - 1 year ago 393
Javascript Question

Youtube iframe api not triggering onYouTubeIframeAPIReady

I've been battling with the youtube iframe api for quite some time now. Somehow the method

is not always triggered.

From the symptoms it seems a loading problem. No errors are shown in the inspector.

Here is my code:


<div id="player"></div>
videoId = 'someVideoId';
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);


(called at the end of the page. I tried to place the code right after the above script and the result was the same.)

var isReady = false
, player
, poster
, video;

$(function () {
$('.js-play').click(function (e) {
interval = setInterval(videoLoaded, 100);
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '445',
width: '810',
videoId: videoId,
events: {
'onReady': onPlayerReady//,
//'onStateChange': onPlayerStateChange

function onPlayerReady(event) {
isReady = true;
console.log("youtube says play")

function videoLoaded (){
if (isReady) {
console.log("ready and play")



The problem is that sometimes nothing gets printed by the
and nothing happens.

On mobile phones this happens all the time. Any ideas?

bcm bcm
Answer Source

It is not a timeout issue, and you should not need to fire this function manually.

Make sure your onYouTubeIframeAPIReady function is available at the global level, not nested (hidden away) within another function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download