用jQuery懒加载html视频

问题描述 投票:0回答:1

我正在尝试懒惰加载我的html视频,它在我的WordPress模板中,我想让视频在用户到达它的视点时加载。它在我的WordPress模板中,我想让视频在用户到达它的视点时加载。

我是JS的新手,所以我觉得有问题。我怎样才能测试懒惰加载是否正确,也许我的功能无效?

<video id="myVideo" autoplay loop muted playsinline src="<?= VIDEO ?>/video_footer.mp4">
    <source data-src="<?= VIDEO ?>/video_footer.mp4" type="video/mp4">
</video>

js:

$(function() {
$("video.myVideo source").each(function() {
    var sourceFile = $(this).attr('data-src');
    $(this).attr("src", sourceFile);
    var video = this.parentElement;
    video.load();
    video.play();
  });
});
html jquery wordpress html5-video
1个回答
2
投票

这是不可能的,因为它是工作。

你已经设置了 sourcevideo 因此,即使功能在工作,视频文件已经存在,所以没有懒惰加载... ...

这就是正确的设置。

<video id="myVideo" autoplay loop muted playsinline src="">
    <source data-src="<?= VIDEO ?>/video_footer.mp4" type="video/mp4">
</video>

然后你可以检查你的功能是否有效


另一种解决方案 是使用 intersection observer 并做 pure JavaScript简单、轻便,在大多数情况下都能使用

用纯JavaScript懒惰加载视频。

<script type="text/javascript">
const lazyvideo = document.querySelectorAll('.lazy-video');
observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.intersectionRatio > 0) {
      console.log('video in the view');
         if (entry.target.querySelector('source').getAttribute('data-src') !== null) {
          const source = entry.target.querySelector('source').getAttribute('data-src')
          entry.target.setAttribute('src', source);
        }
      observer.unobserve(entry.target);
    } else {
      console.log('video out of view');
    }
  });
});

lazyvideo.forEach(video => {
  observer.observe(video);
});
</script>

我已经添加了 console.log('video out of view'); &amp。console.log('video in the view'); 以便在控制台检查视频是否在视图中。

在这个脚本中,如果你想让一个视频被懒惰加载,只需添加一个 class lazy-video 到它,你就可以了;)

完整的代码。

const lazyvideo = document.querySelectorAll('.lazy-video');
observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.intersectionRatio > 0) {
      console.log('video in the view');
         if (entry.target.querySelector('source').getAttribute('data-src') !== null) {
          const source = entry.target.querySelector('source').getAttribute('data-src')
          entry.target.setAttribute('src', source);
        }
      observer.unobserve(entry.target);
    } else {
      console.log('video out of view');
    }
  });
});

lazyvideo.forEach(video => {
  observer.observe(video);
});
#myVideo {
  max-width:400px;
  width:100%;
}
<video id="myVideo" class="lazy-video" autoplay loop muted playsinline src="">
    <source data-src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
</video>

如果你想确定懒惰加载的工作原理

  • 打开你的Chrome开发者工具,然后进入 Network 并选择media 标签
  • 当您打开工具时,重新加载页面
  • 如果你没有滚动到视频部分,那么你应该不会在你的控制台上看到视频。
  • 当你滚动时,当你在视频部分的视图,你必须看到视频加载的媒体标签

请看下面的截图。

还没到

enter image description here

正在查看。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.