lazy loading on multiple embed vimeo video

Viewed 1258

I'm building a portfolio website that contains several embed Vimeo videos and they're slowing down the page loading a lot. So I was thinking of lazy load them so that the browser has to load them only when they actually appear in the page.

I've tried adding the loading="lazy" to the iframe tag but it didn't change anything. So I tried with this code but it seems to work just for one iframe element.

Can you help me understand how to adjust that code to apply the lazyloading to all of the iframe elements in the page?

var iframe = document.querySelector('iframe');

  function handleLazyLoad() {
    if (iframe.classList.contains('lazyload')) {
      const storeSRC = iframe.dataset.src;

      iframe.addEventListener('lazyloaded', () => {
        delete iframe.dataset.src;
        iframe.src = storeSRC;
        initPlayer();
      });
    } 
  }

  function initPlayer() {
    var player = new Vimeo.Player(iframe);
    player.ready().then(function (){
      console.log('player is ready!');

      // These events are not attaching? Why?
      player.on('play', function () {
        console.log('played the video!');
      });

      player.on('ended', function () {
        console.log('the video has ended');
      });
    });
  } 

  handleLazyLoad();
  .content-block {
    width: 200px;
    height: 2000px;
    background-color: red;
  }
<div class="content-block"></div>

<iframe class="lazyload" data-src="https://player.vimeo.com/video/76979871?autoplay=1&muted=1" width="640" height="360" frameborder="0" webkitallowfullscreen
  mozallowfullscreen allowfullscreen allow="autoplay; encrypted-media"></iframe><div style="position: relative;">
                  <div style="padding:53.02% 0 0 0;position:relative;"><iframe src="https://player.vimeo.com/video/495827819?autoplay=1&loop=1&color=c9ff23&title=0&byline=0&portrait=0&autopause=0" style="position:absolute;top:0;left:0;width:100%;height:100%;" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe></div>
</div>
<div style="position: relative;">
                  <div style="padding:53.02% 0 0 0;position:relative;"><iframe src="https://player.vimeo.com/video/495827819?autoplay=1&loop=1&color=c9ff23&title=0&byline=0&portrait=0&autopause=0" style="position:absolute;top:0;left:0;width:100%;height:100%;" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe></div>
</div>

Thank you!

0 Answers
Related