From 68ddbce37bee7db1e664bfc17eaced6a839e5a5e Mon Sep 17 00:00:00 2001 From: Sped0n Date: Tue, 31 Oct 2023 00:06:14 +0800 Subject: [PATCH] feat(collection.ts): add image preloading functionality to improve performance and user experience --- assets/ts/mobile/collection.ts | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/assets/ts/mobile/collection.ts b/assets/ts/mobile/collection.ts index c88600c..f8c08c4 100644 --- a/assets/ts/mobile/collection.ts +++ b/assets/ts/mobile/collection.ts @@ -1,7 +1,7 @@ import { container } from '../container' import { ImageJSON } from '../resources' -import { setIndex } from '../state' -import { getRandom, Watchable } from '../utils' +import { getNextFive, setIndex } from '../state' +import { Watchable, getRandom, onVisible } from '../utils' import { slideUp } from './gallery' /** @@ -44,6 +44,15 @@ export function initCollection(ijs: ImageJSON[]): void { imgs.forEach((img, i) => { img.addEventListener('click', () => handleClick(i)) img.addEventListener('keydown', () => handleClick(i)) + // preload + onVisible(img, () => { + // minues one because we want to preload the current and the next 4 images + getNextFive(i - 1, imgs.length) + .map((i) => imgs[i]) + .forEach((e) => { + e.src = e.dataset.src! + }) + }) }) } @@ -53,8 +62,8 @@ export function initCollection(ijs: ImageJSON[]): void { function createCollection(ijs: ImageJSON[]): void { // create container for images - const collection: HTMLDivElement = document.createElement('div') - collection.className = 'collection' + const _collection: HTMLDivElement = document.createElement('div') + _collection.className = 'collection' // append images to container for (let [i, ij] of ijs.entries()) { // random x and y @@ -62,12 +71,12 @@ function createCollection(ijs: ImageJSON[]): void { const y = i !== 0 ? getRandom(-30, 30) : 0 // element const e = document.createElement('img') - e.src = ij.loUrl + e.dataset.src = ij.loUrl e.height = ij.loImgH e.width = ij.loImgW e.alt = 'image' e.style.transform = `translate3d(${x}%, ${y - 50}%, 0)` - collection.append(e) + _collection.append(e) } - container.append(collection) + container.append(_collection) }