OnYouTubeIframeAPIReady inside jQuery (document) .ready

What I want to do:

  • Wait for the document to be rendered;
  • When the YouTube iframe api is ready, initialize my custom function and pass it a YT object so that I can embed the player from the inside.

This is what I have done so far. It works, but I feel that something is very wrong. I am not sure that this 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 would appreciate it if anyone could clarify that this is the best way to do this. I really need to collect players from inside my_custom_function() .

+6
source share
1 answer

Since the onYouTubeIframeAPIReady function should be in global scope, I suppose we cannot link it in the jQuery document callback. One workaround that I see is using jQuery deferred objects . First we create a deferrable object and enable it in the onYouTubeIframeAPIReady callback

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

and then waiting for the pending object will be resolved after the document is ready

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

See full example in JSFiddle

+6
source

Source: https://habr.com/ru/post/949856/


All Articles