Problems adding iframe code iframe inside document.ready

I want to add iftube iframe api code to my $ (document) .ready () function, but when I do this, the player doesn't seem to load when I move the code outside the document. Can anyone suggest me some or suggestions on how I can make this video appear when inside a function?

Js

$(document).ready(function() { var tag = document.createElement('script'); tag.src = "//www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { height: '390', width: '640', videoId: 'u1zgFlCw8Aw', events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); } function onPlayerReady() { console.log('ready'); } function onPlayerStateChange() { console.log('player changed'); } }); 
+7
source share
2 answers

If you change the function onYouTubePlayerAPIReady() {...} to window.onYouTubePlayerAPIReady = function() {...} , then you can define your iframe API callback in the $(document).ready() function and potentially output other variables from the scope of $(document).ready() to the scope of the callback.

I'm not sure there are many benefits to this, but this is an option if you really want to.

+10
source

The script will call onYouTubePlayerAPIReady() on loading. When you ... say ... "hide" these functions inside your finished DOM wrapper, they are no longer available for the YT API to call (out of scope).

Since you cannot directly access the YT API script file, you cannot change this behavior, and imho what you ask for is impossible.

0
source

All Articles