延迟加载多个嵌入 vimeo 视频

问题描述

我正在构建一个包含多个嵌入 Vimeo 视频的作品集网站,它们大大减慢了页面加载速度。所以我在考虑延迟加载它们,以便浏览器只有在它们实际出现在页面中时才加载它们。

我已经尝试将 loading="lazy" 添加到 iframe 标签,但它没有改变任何东西。所以我尝试了这段代码,但它似乎只适用于一个 iframe 元素。

您能帮我理解如何调整该代码以将延迟加载应用于页面中的所有 iframe 元素吗?

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>

谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)