使用懒加载优化系统消耗

This commit is contained in:
2024-04-11 20:10:02 +08:00
parent 7a5dde7169
commit b950ae8b76
4 changed files with 51 additions and 50 deletions

View File

@@ -1,5 +1,6 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@@ -23,56 +24,49 @@
height: auto;
margin-bottom: 20px;
}
img {
display: block;
width: 100%;
min-height: 100px;
margin-top: 10px;
}
</style>
</head>
<body>
<div id="comic-container"></div>
{% for i in index %}
<img data-src="/api/img/{{ id }}/{{ i }}" loading="lazy" alt="{{ i }}" class="imgs">
{% endfor %}
<div style="display:flex;justify-content: center; align-items:center;">
<img src="/static/loading.gif" id="loadingGIF">
</div>
<script>
var imgs = document.querySelectorAll('.imgs');
<script>
document.addEventListener('DOMContentLoaded', function () {
const comicId = getComicIdFromURL();
if (comicId) {
displayComic(comicId);
} else {
console.error('No comic ID found in URL');
}
});
// 从当前URL中获取漫画ID
function getComicIdFromURL() {
const urlParts = window.location.pathname.split('/');
return urlParts[2]; // 第三部分是漫画ID
}
// 显示漫画
function displayComic(comicId) {
let currentImageIndex = 1;
const comicContainer = document.getElementById('comic-container');
function loadNextImage() {
const imageUrl = `/api/img/${comicId}/${currentImageIndex}`;
fetch(imageUrl)
.then(response => {
if (response.ok) {
const img = document.createElement('img');
img.src = imageUrl;
img.classList.add('comic-image');
comicContainer.appendChild(img);
currentImageIndex++;
// 添加延迟,以控制加载速度
setTimeout(loadNextImage, 500);
} else {
console.error('Error loading image:', response.statusText);
}
})
.catch(error => {
console.error('Error loading image:', error);
});
//offsetTop是元素与offsetParent的距离循环获取直到页面顶部
function getTop(e) {
var T = e.offsetTop;
while (e = e.offsetParent) {
T += e.offsetTop;
}
return T;
}
// 加载第一张图片
loadNextImage();
}
</script>
function lazyLoad(imgs) {
var H = document.documentElement.clientHeight;//获取可视区域高度
var S = document.documentElement.scrollTop || document.body.scrollTop;
for (var i = 0; i < imgs.length; i++) {
if (H + S > getTop(imgs[i])) {
imgs[i].src = imgs[i].getAttribute('data-src');
}
}
}
window.onload = window.onscroll = function () { //onscroll()在滚动条滚动的时候触发
lazyLoad(imgs);
}
</script>
</body>
</html>
</html>