Skip to content
This repository was archived by the owner on Jun 29, 2018. It is now read-only.

Commit 4fe23b3

Browse files
committed
[#963724] Implement our own YouTube ready event by checking and waiting for YT.loaded.
1 parent 7f647e8 commit 4fe23b3

File tree

1 file changed

+28
-27
lines changed

1 file changed

+28
-27
lines changed

wrappers/youtube/popcorn.HTMLYouTubeVideoElement.js

+28-27
Original file line numberDiff line numberDiff line change
@@ -12,43 +12,44 @@
1212

1313
// Setup for YouTube API
1414
ytReady = false,
15-
ytLoaded = false,
15+
ytLoading = false,
1616
ytCallbacks = [];
1717

18+
function onYouTubeIframeAPIReady() {
19+
var callback;
20+
if ( YT.loaded ) {
21+
ytReady = true;
22+
while( ytCallbacks.length ) {
23+
callback = ytCallbacks.shift();
24+
callback();
25+
}
26+
} else {
27+
setTimeout( onYouTubeIframeAPIReady, 250 );
28+
}
29+
}
30+
1831
function isYouTubeReady() {
19-
// If the YouTube iframe API isn't injected, to it now.
20-
if( !ytLoaded ) {
21-
var tag = document.createElement( "script" );
22-
var protocol = window.location.protocol === "file:" ? "http:" : "";
23-
24-
tag.src = protocol + "//www.youtube.com/iframe_api";
25-
var firstScriptTag = document.getElementsByTagName( "script" )[ 0 ];
26-
firstScriptTag.parentNode.insertBefore( tag, firstScriptTag );
27-
ytLoaded = true;
32+
var script;
33+
// If we area already waiting, do nothing.
34+
if( !ytLoading ) {
35+
// If script is already there, check if it is loaded.
36+
if ( window.YT ) {
37+
onYouTubeIframeAPIReady();
38+
} else {
39+
script = document.createElement( "script" );
40+
script.addEventListener( "load", onYouTubeIframeAPIReady, false);
41+
script.src = "https://www.youtube.com/iframe_api";
42+
document.head.appendChild( script );
43+
}
44+
ytLoading = true;
2845
}
2946
return ytReady;
3047
}
3148

3249
function addYouTubeCallback( callback ) {
33-
ytCallbacks.unshift( callback );
50+
ytCallbacks.push( callback );
3451
}
3552

36-
// An existing YouTube references can break us.
37-
// Remove it and use the one we can trust.
38-
if ( window.YT ) {
39-
window.quarantineYT = window.YT;
40-
window.YT = null;
41-
}
42-
43-
window.onYouTubeIframeAPIReady = function() {
44-
ytReady = true;
45-
var i = ytCallbacks.length;
46-
while( i-- ) {
47-
ytCallbacks[ i ]();
48-
delete ytCallbacks[ i ];
49-
}
50-
};
51-
5253
function HTMLYouTubeVideoElement( id ) {
5354

5455
// YouTube iframe API requires postMessage

0 commit comments

Comments
 (0)