Optimizing Lazy Loading for Image Preview in el-image Component
Problem Overview
In the project, images are categorized into two forms: thumbnails (small) and full-resolution versions (full). Thumbnails are displayed initially, while full-resolution images are shown up on user interaction through the el-image component. The component's preview-src-list prop expects an array of full-resolution image URLs. However, clicking a thumbnail triggers loading of all images in the list, leading to unnecessary resource consumption and slower load times.
Requirements
- Handle two types of images: small thumbnails and full-resolution images.
- Enable preview of full-resolution images with navigation capability.
- Load only the currently selected image’s full-resolution version.
Initial Implementation
The initial implementation loads all full-resolution images at once:
<template>
<div v-for="(img, index) in imgsInfo" :key="img.small">
<el-image
:src="img.small"
lazy
loading="lazy"
fit="contain"
:preview-src-list="previewImagesList"
:initial-index="index"
:hide-on-click-modal="true">
</el-image>
</div>
</template>
<script setup>
const imgsInfo = ref([{"small": "http://xxx/id/small.jpg", "full": "http://xxx/id/full.jpg"}, {...}]);
const previewImagesList = computed(() => {
return imgsInfo.map((item) => item.full);
});
</script>
As demonstrated, when a user opens the preview, all full-resolution images are fetched, not just the one being viewed.
Optimized Approach
To address this issue, we initialize the preview list with empty strings and populate it dynamically when needed:
<template>
<div v-for="(img, index) in imgsInfo" :key="img.small">
<el-image
:src="img.small"
lazy
loading="lazy"
fit="contain"
:preview-src-list="previewImagesList"
:initial-index="index"
:hide-on-click-modal="true"
@switch="previewImages"
@show="previewImages(index)">
</el-image>
</div>
</template>
<script setup>
const imgsInfo = ref([
{"small": "http://xxx/id/small.jpg", "full": "http://xxx/id/full.jpg"},
{...}
]);
const previewImagesList = computed(() => {
return new Array(imgsInfo.value.length).fill("");
});
const previewImages = (index) => {
if (!previewImagesList.value[index]) {
previewImagesList.value[index] = imgsInfo.value[index].full;
}
};
</script>
This solution ensures that only the requested full-ressolution image is loaded during preview, preserving performance and supporting seamlesss navigation between images.