onYouTubeIframeAPIReady inside jQuery(document).ready
api, iframe, javascript, youtube
Solution
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
Problem
What I want to do is: - Wait for the document to render; - 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()`.