微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

延迟加载多个嵌入 vimeo 视频

如何解决延迟加载多个嵌入 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 举报,一经查实,本站将立刻删除。