我正在尝试懒惰加载我的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();
});
});
这是不可能的,因为它是工作。
你已经设置了 source
到 video
因此,即使功能在工作,视频文件已经存在,所以没有懒惰加载... ...
这就是正确的设置。
<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>
如果你想确定懒惰加载的工作原理
Network
并选择media
标签请看下面的截图。
还没到
正在查看。