diff --git a/wrappers/youtube/popcorn.HTMLYouTubeVideoElement.js b/wrappers/youtube/popcorn.HTMLYouTubeVideoElement.js
index 5e3fc8133..f0e090197 100644
--- a/wrappers/youtube/popcorn.HTMLYouTubeVideoElement.js
+++ b/wrappers/youtube/popcorn.HTMLYouTubeVideoElement.js
@@ -12,43 +12,44 @@
// Setup for YouTube API
ytReady = false,
- ytLoaded = false,
+ ytLoading = false,
ytCallbacks = [];
+ function onYouTubeIframeAPIReady() {
+ var callback;
+ if ( YT.loaded ) {
+ ytReady = true;
+ while( ytCallbacks.length ) {
+ callback = ytCallbacks.shift();
+ callback();
+ }
+ } else {
+ setTimeout( onYouTubeIframeAPIReady, 1000 );
+ }
+ }
+
function isYouTubeReady() {
- // If the YouTube iframe API isn't injected, to it now.
- if( !ytLoaded ) {
- var tag = document.createElement( "script" );
- var protocol = window.location.protocol === "file:" ? "http:" : "";
-
- tag.src = protocol + "//www.youtube.com/iframe_api";
- var firstScriptTag = document.getElementsByTagName( "script" )[ 0 ];
- firstScriptTag.parentNode.insertBefore( tag, firstScriptTag );
- ytLoaded = true;
+ var script;
+ // If we area already waiting, do nothing.
+ if( !ytLoading ) {
+ // If script is already there, check if it is loaded.
+ if ( window.YT ) {
+ onYouTubeIframeAPIReady();
+ } else {
+ script = document.createElement( "script" );
+ script.addEventListener( "load", onYouTubeIframeAPIReady, false);
+ script.src = "https://www.youtube.com/iframe_api";
+ document.head.appendChild( script );
+ }
+ ytLoading = true;
}
return ytReady;
}
function addYouTubeCallback( callback ) {
- ytCallbacks.unshift( callback );
+ ytCallbacks.push( callback );
}
- // An existing YouTube references can break us.
- // Remove it and use the one we can trust.
- if ( window.YT ) {
- window.quarantineYT = window.YT;
- window.YT = null;
- }
-
- window.onYouTubeIframeAPIReady = function() {
- ytReady = true;
- var i = ytCallbacks.length;
- while( i-- ) {
- ytCallbacks[ i ]();
- delete ytCallbacks[ i ];
- }
- };
-
function HTMLYouTubeVideoElement( id ) {
// YouTube iframe API requires postMessage