Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy Load youtube video from iframe API

I want to lazy load the youtube video with iframe API. ie. load only the poster image in the beginning and when user clicks on it then only load the actual image and its content.

like image 249
madhuhc Avatar asked Jun 16 '16 10:06

madhuhc


2 Answers

Most of this is taken from the getting started section on the youtube page.

<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
    <div id="player"></div>

    <script>
      // 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');

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

      // 3. This function creates an <iframe> (and YouTube player)
      //    after the API code downloads.
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'M7lc1UVf-VE',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }

      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        event.target.playVideo();
      }

      // 5. The API calls this function when the player's state changes.
      //    The function indicates that when playing a video (state=1),
      //    the player should play for six seconds and then stop.
      var done = false;
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
          setTimeout(stopVideo, 6000);
          done = true;
        }
      }
      function stopVideo() {
        player.stopVideo();
      }
    </script>

This example loads the video when it is ready.

So we change it up a bit to add in a placeholder image and on click hide the image and play the video.

Wrap the tag (step 2) in function

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

Add an image Check this question for more details on sizes.

<div id="placeholder">
    <img src="http://img.youtube.com/vi/M7lc1UVf-VE/sddefault.jpg" />
</div>

Then on click hide the placeholder image and load the player

document.getElementById("placeholder").addEventListener("click", function(){
    this.style.display = 'none';
    loadYT()
});

Final result can be seen below.

<div id="placeholder">
<img src="http://img.youtube.com/vi/M7lc1UVf-VE/sddefault.jpg" />
</div>
</div>
<div id="player"></div>

<script>

document.getElementById("placeholder").addEventListener("click", function(){
    this.style.display = 'none';
    loadYT()
});
  // 2. This code loads the IFrame Player API code asynchronously.
  function loadYT() {
    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  }

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;

  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;

  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }

  function stopVideo() {
    player.stopVideo();
  }

</script>
like image 116
ak85 Avatar answered Sep 28 '22 07:09

ak85


Why load the videos on click, and not just when the user sees them? Use jQuery.Lazy and you have nothing more to do. :)

Add the Plugin to your Page: (you will need jQuery or Zepto as well)

<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazy/1.7.1/jquery.lazy.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazy/1.7.1/plugins/jquery.lazy.youtube.min.js"></script>

Prepare your iFrames: (note the data-loader and data-src attributes)

<iframe data-loader="youtube" data-src="1AYGnw6MwFM" width="560" height="315"></iframe>

And start using Lazy:

$(function() {
    $("iframe[data-src]").Lazy();
});

That's it! The iFrames will be loaded whenever the user reaches them by scrolling. More inormations here.

like image 35
eisbehr Avatar answered Sep 28 '22 09:09

eisbehr