Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading YouTube API in jQuery

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?

like image 746
Daniel Avatar asked Aug 09 '13 02:08

Daniel


2 Answers

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
      }
    });
  }
};
like image 102
Jeff Posnick Avatar answered Oct 04 '22 11:10

Jeff Posnick


poor man's solution, but ...

function readyYoutube(){
    if((typeof YT !== "undefined") && YT && YT.Player){
        player = new YT.Player('player', {
            ...
        });
    }else{
        setTimeout(readyYoutube, 100);
    }
}
like image 32
user151496 Avatar answered Oct 04 '22 11:10

user151496