feat(gallery.ts): change image source to a data attribute and dynamically load it when the image is visible

This commit is contained in:
Sped0n
2023-10-30 17:47:06 +08:00
parent b5aae19c70
commit 071f53071e
3 changed files with 26 additions and 7 deletions

View File

@@ -62,9 +62,9 @@ function createCollection(ijs: ImageJSON[]): void {
const y = i !== 0 ? getRandom(-30, 30) : 0
// element
const e = document.createElement('img')
e.src = ij.url
e.height = ij.imgH
e.width = ij.imgW
e.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)

View File

@@ -3,7 +3,7 @@ import Swiper from 'swiper'
import { container } from '../container'
import { ImageJSON } from '../resources'
import { setIndex, state } from '../state'
import { Watchable, expand } from '../utils'
import { Watchable, expand, onVisible } from '../utils'
import { imgs, mounted } from './collection'
import { scrollable } from './scroll'
@@ -104,8 +104,7 @@ export function initGallery(ijs: ImageJSON[]): void {
*/
function changeSlide(slide: number): void {
console.log(slide)
swiper?.slideTo(slide, 0)
swiper!.slideTo(slide, 0)
}
function scrollToActive(): void {
@@ -150,8 +149,13 @@ function createGallery(ijs: ImageJSON[]): void {
_swiperSlide.className = 'swiper-slide'
// img
const e = document.createElement('img')
e.src = ij.url
e.dataset.src = ij.hiUrl
e.height = ij.hiImgH
e.width = ij.hiImgW
e.alt = 'image'
onVisible(e, (e) => {
e.src = e.dataset.src!
})
// append
_swiperSlide.append(e)
_swiperWrapper.append(_swiperSlide)

View File

@@ -22,6 +22,21 @@ export function getRandom(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
export function onVisible(
element: HTMLImageElement,
callback: (arg0: HTMLImageElement) => void
) {
new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.intersectionRatio > 0) {
callback(element)
observer.disconnect()
}
})
}).observe(element)
if (!callback) return new Promise((r) => (callback = r))
}
/**
* custom types
*/