admin管理员组

文章数量:1316030

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(""); // 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().

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./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().

Share Improve this question edited Sep 15, 2015 at 18:57 Michael Radionov 13.3k2 gold badges58 silver badges75 bronze badges asked Jul 19, 2013 at 18:56 ZhivkoZhivko 5505 silver badges17 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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

本文标签: javascriptonYouTubeIframeAPIReady inside jQuery(document)readyStack Overflow