gpt4 book ai didi

javascript - 什么时候开始删除视频元素以防止浏览器延迟?

转载 作者:太空狗 更新时间:2023-10-29 13:14:39 25 4
gpt4 key购买 nike

我正在尝试制作一个网站,该网站会在页面向下滚动时继续向页面添加视频播放器。虽然我担心页面上的大量视频播放器会导致网站延迟并导致网站速度变慢。我想我在对我的网站进行一些测试时遇到了速度下降的问题。那么是否可以检测网站是否因网络上的元素数量而变慢,这样我就可以开始从页面顶部删除视频元素?

index.html:

window.onbeforeunload = function () {
this.scrollTo(0, 0);
}

var content = document.getElementById("content"),
timeout = undefined;

for (var x=0;x<50;x++) {
var video = document.createElement("video");
video.style.backgroundColor = "orange";
video.poster = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/Big_buck_bunny_poster_big.jpg/220px-Big_buck_bunny_poster_big.jpg";
video.src = "https://dash.akamaized.net/akamai/bbb/bbb_3840x2160_60fps_18000k.mp4";
video.controls = true;
content.appendChild(video);
}

window.addEventListener("scroll", function () {
var $this = this;
window.clearTimeout(timeout);
timeout = setTimeout(function() {
var content_margin_top = $this.innerHeight * 0.11;
var last_player = content.children[content.querySelectorAll("video").length - 1];
if (last_player.offsetTop - content_margin_top <= $this.scrollY) {
for (var x=0;x<10;x++) {
var video = document.createElement("video");
video.style.backgroundColor = "orange";
video.poster = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/Big_buck_bunny_poster_big.jpg/220px-Big_buck_bunny_poster_big.jpg";
video.src = "https://dash.akamaized.net/akamai/bbb/bbb_3840x2160_60fps_18000k.mp4";
video.controls = true;
content.appendChild(video);
}
}
}, 250);
});
body {
margin: 0;
}
#nav {
width: 100%;
height: 10%;
position: absolute;
top: 0;
background-color: rgb(108, 171, 247);
}
#content {
height: 100%;
width: 98%;
position: absolute;
top: 11%;
left: 1%;
}
video {
width: 100%;
height: 75%;
border: 1px solid black;
}
<html>
<head>
<title></title>
</head>
<body>
<div id="nav"></div>
<div id="content"></div>
</body>
</html>

最佳答案

我会以稍微不同的方式思考这个问题:我应该怎么做才能使该页面尽可能快地工作,下载尽可能少的数据并在需要时只呈现必要的容器?

我的建议:

1) 不要在滚动期间附加和初始化视频容器。使用 img 标签只渲染 future 视频容器的缩略图。还应考虑对这些图像进行延迟加载。将“播放”按钮添加到预览容器的中心。一旦用户点击按钮 - 使用适当的 src 呈现 video 标签并播放它。

2) 不要使用滚动事件监听器来检测容器偏移和延迟加载。使用 Intersection API相反。

关于javascript - 什么时候开始删除视频元素以防止浏览器延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54229148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com