title: YouTube API not loading consistently
body: <p>For the college I work for I am trying to get a youtube video to auto play in the banner of the webpage. The API is not loading every time properly. I am not sure what I could do to try to fix this. </p>
  
  <p>I have tried:</p>
  
  <ul>
  <li><p>Moving the adding of the youtube API script to only when the DOM is ready. </p></li>
  <li><p>Placing the code on the top and bottom of the page. </p></li>
  <li><p>Checking to see if the player object was created properly and if not try to recreate it which I learned breaks the API.</p></li>
  </ul>
  
  <p>If I strip the page of everything and just have the banner the video loads more often but still not 100% of the time. </p>
  
  <p>Here I provided the script on the page that is loading the video via the YouTube API.</p>
  
  <p>Update:
  From what I can tell by logging to the console the player object is not being fully initialized. 
  When it is not created correctly this is what the object print out looks like:</p>
  
  <pre><code>Y {b: null, a: null, h: null, closure_uid_165988549: 1, g: 1, …}
  </code></pre>
  
  <p>And here it is when is done correctly:</p>
  
  <pre><code>Y {b: Wa, a: iframe#ytplayer, h: div#ytplayer, closure_uid_16195269: 1, g: 1, …}
  </code></pre>
  
  <p>I was wrong about it not finding the videoId. The video is set every time before the function is called so it should not be an issue. </p>
  
  <pre><code>&lt;div id="ytplayer"&gt;&lt;/div&gt;
  
    &lt;script&gt;
      defer(function() {if(window.mobile === true) { $('#ytplayer').remove(); }});
       var ready;
      // Replace the 'ytplayer' element with an &lt;iframe&gt; and
      // YouTube player after the API code downloads.
      var player;
      // var videoId = 'ZCESafUzSRo';
    function onYouTubeIframeAPIReady() {
        checkFunction();
      }
  
      function checkFunction() {
        console.log("checkFunction called");
        setYTready(ready);
      }
      function setYTready(ready) {
        console.log("setYT ready called");
        ready = true;
        mtuPlayerCreate(player);
      }
  
      function mtuPlayerCreate(player) {
        console.log("mtu create called");
  
  
  
        if((player == undefined) &amp;&amp; ( document.getElementById("play-yt") != null)) {
      console.log("Creating player");
        player = new YT.Player('ytplayer', {
          height: '52.65%',
          width: '100%',
          playerVars: {
            'controls': 0,
            'showinfo': 0,
            'rel': 0,
            'iv_load_policy': 3
          },
          videoId: videoId,
          events: {
            'onReady': onPlayerReady,
            // Removing the following if loop shouldn't be enabled
            onStateChange: 
            function(e){
              if (e.data === YT.PlayerState.ENDED) {
                player.playVideo(); 
              }
            }
          }
        });
  
      }
      console.log("player redo below");
      console.log(player);
        if(player.A == false) {
        //setTimeout(function() {location.reload();}, 2000); 
      } else {
        return;
      }
    }
  
  
      function onPlayerReady(event) { /* configuring default playing and mute settings */
        console.log("on ready has been called")
        var autoPlay = 1;
        var autoMute = 1;
        if(autoPlay === 1) { event.target.playVideo(); }
        if(document.getElementById('play-yt') &amp;&amp; autoPlay === 1) { document.getElementById('play-yt').className = 'pause'; }else if(document.getElementById('play-yt')) { document.getElementById('play-yt').className = 'play'; }
        if(autoMute === 1) { event.target.mute(); }
        if(document.getElementById('mute-yt') &amp;&amp; autoMute === 1) { document.getElementById('mute-yt').className = 'mute'; }else if(document.getElementById('mute-yt')) { document.getElementById('mute-yt').className = 'loud'; }
        if(document.getElementById('yt-yt')) { document.getElementById('yt-yt').className = ''; }
      }
  
      window.onload = function() { /* this handles what happens when the player and its buttons are clicked on */
  
              document.getElementsByClassName('media-black')[0].onclick=function(e) { 
          if(e.target.id !== 'yt-yt' &amp;&amp; e.target.id !== 'mute-yt') {
            if(player.getPlayerState() === -1 || player.getPlayerState() === 2  || player.getPlayerState() === 5) {  
              player.playVideo(); 
              if(document.getElementById('play-yt')) { document.getElementById('play-yt').className = 'pause'; }
              if (window._gaq) _gaq.push(['_trackEvent', 'Wide Video', 'Played', window.location.href]);
            }else{
              player.pauseVideo(); 
              if(document.getElementById('play-yt')) { document.getElementById('play-yt').className = 'play'; }
              if (window._gaq) _gaq.push(['_trackEvent', 'Wide Video', 'Paused', window.location.href]);
            }
          }
          else if(e.target.id === 'yt-yt' &amp;&amp; e.target.id !== 'mute-yt') {
            window.open('http://www.youtube.com/watch?v=' + videoId, '_blank');
            player.pauseVideo();
            if(document.getElementById('play-yt') &amp;&amp; document.getElementById('play-yt').className === 'pause') { document.getElementById('play-yt').className = 'play'; }
            if (window._gaq) _gaq.push(['_trackEvent', 'Wide Video', 'Went to YouTube', window.location.href]);
          }else{
            if(player.isMuted() || player.getVolume() === 0) { player.unMute(); player.setVolume(100); document.getElementById('mute-yt').className = 'loud'; }else{ player.mute(); document.getElementById('mute-yt').className = 'mute'; }
            if (window._gaq) _gaq.push(['_trackEvent', 'Wide Video', 'Sound Adjusted', window.location.href]);
          }
        };
  
  
  
      }
  
      //
      //This could be improved, test if it's mobile and load if not instead of loading and then removing if mobile
      //
      // Load the IFrame Player API code asynchronously.
      document.addEventListener("DOMContentLoaded", function(event) { 
        console.log("dom ready!");
      var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    });
    &lt;/script&gt; 
  &lt;/div&gt;
  </code></pre>
  
  <p>What it needs to do is:</p>
  
  <ol>
  <li>Load the API</li>
  <li>Load the player object with the given video ID</li>
  <li>Add the iframe to the correct spot</li>
  <li>Autoplay the video. </li>
  </ol>
  
  <p>It needs to do this every time the page loads. </p>