当一个页面充满了精美图片时,为了让用户体验更流畅,并避免加载所有图片导致页面卡顿或带宽浪费,图片懒加载便成为了救星。而这其中,滚动加载 和 分页控制 是实现懒加载的核心策略。通过监听用户滚动位置动态加载图片,加之对图片数据的分页处理,我们能够在性能与体验之间找到平衡。
滚动加载的思路并不复杂,但要让它既灵敏又高效,需要关注细节。想象一个用户快速向下滚动时,如果我们实时捕捉滚动事件,并不断检查是否需要加载新图片,很可能造成性能瓶颈。为此,我们需要为滚动事件添加触发阈值。
在这段代码中,handleScroll
方法负责监听滚动事件,并判断用户是否接近页面底部:
handleScroll() {
const { scrollTop, clientHeight, scrollHeight } = this.$el;
// 当滚动位置接近底部 200px 时,触发加载逻辑
if (!this.isLoading && this.currentPage <= this.totalPages && scrollTop + clientHeight >= scrollHeight - 200) {
this.fetchImages();
}
}
scrollTop
是滚动条距离顶部的高度。clientHeight
是可见区域的高度。scrollHeight
是整个内容区域的总高度。一旦用户的滚动位置触及scrollHeight - 200
的阈值,就会调用fetchImages
加载下一批图片。在这里,“200”是一个灵活的值,可以根据页面滚动速度和内容动态调整。
为了避免一次性加载过多图片,分页机制将图片数据分块加载。通过 currentPage
和 perPage
两个变量,我们能够清晰地知道当前加载到了第几页,以及每页需要加载的图片数量。
async fetchImages() {
if (this.isLoading) return;
this.isLoading = true; // 防止重复加载
try {
const response = await axios.post("/get-gallery-images", {
id: this.galleryId.id,
gallery: this.galleryId.name,
page: this.currentPage,
page_size: this.perPage,
});
const { images, total } = response.data;
// 为每张图片生成唯一 ID
const imagesWithId = images.map((image, index) => ({
...image,
id: `${this.currentPage}-${index}`,
}));
this.images = [...this.images, ...imagesWithId]; // 合并新旧图片
this.totalPages = Math.ceil(total / this.perPage); // 计算总页数
this.currentPage++; // 更新页码
} catch (error) {
console.error("获取图片失败:", error);
} finally {
this.isLoading = false;
}
}
currentPage
和 perPage
发送至服务器,我们精确地请求当前所需的图片数据。images
数组中,确保新旧图片能无缝显示。perPage
用户使用不同设备时,屏幕尺寸和分辨率会有较大差异。因此,每页加载的图片数量也不应固定。通过计算屏幕高度与网格列数,我们能够灵活设置 perPage
:
calculatePerPage() {
const itemHeight = 200; // 每个图片块的高度
const screenHeight = window.innerHeight; // 屏幕高度
const itemsPerColumn = Math.floor(screenHeight / itemHeight);
const itemsPerRow = this.$el
? Math.floor(this.$el.offsetWidth / 150) // 根据容器宽度动态计算每行显示的图片数
: 1;
this.perPage = itemsPerColumn * itemsPerRow;
}
这个方法在页面初始化和窗口大小变化时触发,确保页面无论在哪种设备上都能高效显示。
通过滚动加载捕捉用户的交互意图,通过分页控制分步加载数据,这种懒加载方案不仅能有效缓解性能压力,还能提供流畅的用户体验。在实现的过程中,代码与逻辑的结合需要我们持续优化,为每一帧滚动画面注入丝滑的灵动感。