diff --git a/frontend/src/b/storyImage.ts b/frontend/src/b/storyImage.ts index 452d970..b2ea1f0 100644 --- a/frontend/src/b/storyImage.ts +++ b/frontend/src/b/storyImage.ts @@ -165,6 +165,37 @@ function encode(canvas: HTMLCanvasElement, format: 'png' | 'jpeg'): Promise canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/png')) } +const LAZY_IMAGE_WAIT_MS = 8000 + +/** 이미지 한 장이 불러와져 디코딩될 때까지. 실패하거나 느려도 LAZY_IMAGE_WAIT_MS 넘게는 기다리지 않는다 (캡처 라이브러리가 자체로 다시 받는다) */ +function loadImage(img: HTMLImageElement): Promise { + return new Promise((resolve) => { + const timer = setTimeout(resolve, LAZY_IMAGE_WAIT_MS) + img.decode().then( + () => undefined, + () => undefined, + ).then(() => { + clearTimeout(timer) + resolve() + }) + }) +} + +/** + * 캐러셀 밖 슬라이드의 loading="lazy" 이미지는 화면에 들어오기 전엔 불러오지 않는다. + * 캡처 라이브러리는 원본 화면 이미지의 로드 이벤트를 타임아웃(30초)까지 기다리므로, 캡처 전에 eager 로 바꿔 바로 불러온다 + * (날씨각 카드 공유가 웹·앱 모두 약 30초 걸리던 원인). + */ +function loadLazyImages(roots: HTMLElement[]): Promise { + const pending = roots + .flatMap((r) => (r instanceof HTMLImageElement ? [r] : Array.from(r.querySelectorAll('img')))) + .filter((img) => img.loading === 'lazy' && !img.complete) + pending.forEach((img) => { + img.loading = 'eager' + }) + return Promise.all(pending.map(loadImage)) +} + /** 게시물 슬라이드(최대 2장)를 고른 크기의 이미지 한 장으로 만든다. 기본은 PNG, 앱은 JPEG */ export async function shareImage(slides: HTMLElement[], opts: { size: ShareSize; sky: string; sub: string; host: string; format?: 'png' | 'jpeg' }): Promise { const z = SHARE_SIZES[opts.size] @@ -176,6 +207,7 @@ export async function shareImage(slides: HTMLElement[], opts: { size: ShareSize; document.fonts.load(LOGO(36), '12'), document.fonts.load(SANS(z.subPx), opts.sub), ...(z.strip ? [] : [document.fonts.load(SANS(z.labelPx), PILL_LABEL)]), + loadLazyImages(cards), ]) const css = await fontCss(cards.map((c) => c.textContent ?? '').join('')) const aspect = cards[0].offsetHeight / cards[0].offsetWidth