What is the purpose of the load function?

Oh, and no it doesn’t prevent the youtube api from being caught in the browser. When testing on local pages where things happen fast, that problem can still occur.

The load code does not protect from that.

Use onYouTubeIframeAPIReady and that problem no longer exists.

This would be for when no cover is used.
https://jsfiddle.net/78ndxtm3/2/


const videoPlayer = (function makeVideoPlayer() {
  "use strict";

  let player

  const tag = document.createElement('script');
  tag.src = "https://www.youtube.com/iframe_api";
  const firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);


  function onPlayerReady(event) {
    const player = event.target;
    player.setVolume(100); // percent
  }
  let hasShuffled = false;

  function onPlayerStateChange(event) {
    const player = event.target;
    const shufflePlaylist = true;

    if (!hasShuffled) {
      player.setShuffle(shufflePlaylist);
      player.playVideoAt(0);
      hasShuffled = true;
    }
  }

  function addPlayer(video) {
    const playlist = "0dgNc5S8cLI,mnfmQe8Mv1g,-Xgi_way56U,CHahce95B1g";
    new YT.Player(video, {

      width: 640,
      height: 360,
      host: "https://www.youtube-nocookie.com",
      playerVars: {
        autoplay: 1,
        controls: 1,
        loop: 1,
        rel: 0,
        iv_load_policy: 3,
        cc_load_policy: 0,
        fs: 0,
        disablekb: 1,
        playlist
      },
      events: {
        "onReady": onPlayerReady,
        "onStateChange": onPlayerStateChange
      }
    });
  }

  function play() {
    player.playVideo();
  }
  return {
    addPlayer,
    play
  };
}());

function onYouTubeIframeAPIReady() {
  const frameContainer = document.querySelector(".video");
  videoPlayer.addPlayer(frameContainer);
}

Let’s look back at the code changes I posted at post #34

All is good until we get down to the addPlayer part. We need to be able to access the addPlayer function, and have the onYouTubeIframeAPIReady use that addPlayer function.

First, provide access to the addPlayer function, removing the init code too while we’re at it because it’s not used anymore:

  // function init(opts) {
  //   addPlayer(opts.video);
  // }
  return {
    // init
    addPlayer
  };
}());

Then we replace the videoPlayer.init code with the onYouTubeIframeAPIReady

// videoPlayer.init({
//   video: document.querySelector(".video")
// });
function onYouTubeIframeAPIReady() {
    const frameContainer = document.querySelector(".video");
    videoPlayer.addPlayer(frameContainer);
}

That’s it. https://jsfiddle.net/1codzwb4/

1 Like

52 posts were split to a new topic: Why does autoplay start playing the video?