feat(collection.ts): add image preloading functionality to improve performance and user experience

This commit is contained in:
Sped0n
2023-10-31 00:06:14 +08:00
parent 6606dcec93
commit 68ddbce37b

View File

@@ -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)
}