|
12 | 12 |
|
13 | 13 | // Setup for YouTube API
|
14 | 14 | ytReady = false,
|
15 |
| - ytLoaded = false, |
| 15 | + ytLoading = false, |
16 | 16 | ytCallbacks = [];
|
17 | 17 |
|
| 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 | + |
18 | 31 | 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; |
28 | 45 | }
|
29 | 46 | return ytReady;
|
30 | 47 | }
|
31 | 48 |
|
32 | 49 | function addYouTubeCallback( callback ) {
|
33 |
| - ytCallbacks.unshift( callback ); |
| 50 | + ytCallbacks.push( callback ); |
34 | 51 | }
|
35 | 52 |
|
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 |
| - |
52 | 53 | function HTMLYouTubeVideoElement( id ) {
|
53 | 54 |
|
54 | 55 | // YouTube iframe API requires postMessage
|
|
0 commit comments