我的页面顶部有一个视频元素,我想知道在加载 DOM 的其余部分后是否有任何方法可以加载它?我希望视频最后加载。
问问题
1728 次
2 回答
3
这似乎做你想做的事。在我的示例中,我只包含了一个 mp4 源,但您可以根据您支持的浏览器为 WebM 和 Ogg 添加其他源。您可以简单地填充所有三个属性,或者使用 canPlayType 测试来确定最适合用户浏览器的属性。
video 元素默认为自动播放(但您可以从标签中删除该属性<video...>
并直接从脚本中控制它。它还默认preload="auto"
让浏览器控制预加载量,如果它不是最佳的,您可能希望再次关闭它对于您的场景(不同的浏览器有非常不同的行为)
您可能还想隐藏视频元素,直到您准备好加载内容(尽管这会使页面有点晃动,并且对用户来说可能看起来很奇怪)
<!DOCTYPE html>
<html>
<head>
<title>Initialize video when doc is ready</title>
<script>
document.onreadystatechange = function () {
console.log("readyState = " + document.readyState);
if (document.readyState == "interactive") { // can also wait for "complete" here
init();
}
}
function init() {
console.log("load the source for the video element")
vid = document.getElementById("video")
// can use the vid.canPlayType test to only load supported video
// or have tags for MP4, WebM and Ogg to cover your bases
vidMP4 = document.getElementById("videoMP4")
vidMP4.setAttribute("src","video.mp4")
// vid.play();
}
</script>
</head>
<body>
<p>Something before the video</p>
<video id="video" controls autoplay preload="auto" width=480 height=320>
<source id="videoMP4"></source></video>
<p>Something after the video</p>
</body>
</html>
于 2013-08-17T23:44:04.887 回答
1
Google has some good guidance on this here.
In summary, change the src
attributes to data-src
attributes, and add a lazy
class for targeting, e.g.:
<video class="lazy" autoplay muted loop playsinline width="610" height="254" poster="one-does-not-simply.jpg">
<source data-src="one-does-not-simply.webm" type="video/webm">
<source data-src="one-does-not-simply.mp4" type="video/mp4">
</video>
Then use the following JavaScript to flip the data-src
attributes to src
attributes and trigger loading of the video:
document.addEventListener("DOMContentLoaded", function() {
var lazyVideos = [].slice.call(document.querySelectorAll("video.lazy"));
if ("IntersectionObserver" in window) {
var lazyVideoObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(video) {
if (video.isIntersecting) {
for (var source in video.target.children) {
var videoSource = video.target.children[source];
if (typeof videoSource.tagName === "string" && videoSource.tagName === "SOURCE") {
videoSource.src = videoSource.dataset.src;
}
}
video.target.load();
video.target.classList.remove("lazy");
lazyVideoObserver.unobserve(video.target);
}
});
});
lazyVideos.forEach(function(lazyVideo) {
lazyVideoObserver.observe(lazyVideo);
});
}
});
于 2020-05-11T12:37:39.210 回答