Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onYouTubeIframeAPIReady inside jQuery(document).ready

What I want to do is:

  1. Wait for the document to render;
  2. When YouTube iframe api is ready, initialize my custom function and pass the YT object to it so I can build the player from inside.

This is what I have done so far. It works but I have feeling something is very wrong. I am not sure it should be done this way.

jQuery.getScript("http://www.youtube.com/iframe_api"); // load YT api

jQuery(document).ready(function() {
  onYouTubeIframeAPIReady = function() {
    new my_custom_function().init(YT); // init my function and pass YT object
  };
});

I'd appreciate it if someone can clarify what's the best way to do this. I do really need to build the players from inside my_custom_function().

like image 471
Zhivko Avatar asked Jul 19 '13 18:07

Zhivko


1 Answers

As onYouTubeIframeAPIReady function has to be in a global scope, I suppose we can't bind it in jQuery's document ready callback. One of the workarounds I see is to use jQuery deferred objects. At first we create a deffered object and resolve it in onYouTubeIframeAPIReady callback

 var YTdeferred = $.Deferred();
 window.onYouTubeIframeAPIReady = function() {
   YTdeferred.resolve(window.YT);
 };

and then waiting for deferred object to be resolved after document ready

$(document).ready(function() {
  YTdeferred.done(function(YT) {
    // use YT here
  });
});

See the full example on JSFiddle

like image 122
Michael Radionov Avatar answered Nov 13 '22 05:11

Michael Radionov