pstream is dead; long live pstream taciturnaxolotl.github.io/pstream-ng/
at main 55 lines 1.8 kB view raw
1/** 2 * Global image fade-in handler 3 * Automatically adds 'loaded' class to images when they finish loading 4 */ 5export function initializeImageFadeIn() { 6 // Handle images that are already loaded (cached) 7 const handleExistingImages = () => { 8 const images = document.querySelectorAll(`img:not(.no-fade):not([src=""]`); 9 images.forEach((img) => { 10 const htmlImg = img as HTMLImageElement; 11 if (htmlImg.complete && htmlImg.naturalHeight !== 0) { 12 htmlImg.classList.add("loaded"); 13 } 14 }); 15 }; 16 17 // Handle images that load after DOM is ready 18 const handleImageLoad = (e: Event) => { 19 const img = e.target as HTMLImageElement; 20 if (img.tagName === "IMG") { 21 img.classList.add("loaded"); 22 } 23 }; 24 25 // Use event delegation for all images (including dynamically added ones) 26 document.addEventListener("load", handleImageLoad, true); 27 28 // Handle existing images on initialization 29 if (document.readyState === "loading") { 30 document.addEventListener("DOMContentLoaded", handleExistingImages); 31 } else { 32 handleExistingImages(); 33 } 34 35 // Also check periodically for images that might have loaded 36 // This handles edge cases where the load event might not fire 37 const checkInterval = setInterval(() => { 38 const images = document.querySelectorAll(`img:not(.no-fade):not([src=""]`); 39 if (images.length === 0) { 40 clearInterval(checkInterval); 41 return; 42 } 43 images.forEach((img) => { 44 const htmlImg = img as HTMLImageElement; 45 if (htmlImg.complete && htmlImg.naturalHeight !== 0) { 46 htmlImg.classList.add("loaded"); 47 } 48 }); 49 }, 100); 50 51 // Clean up interval after 10 seconds to avoid memory leaks 52 setTimeout(() => { 53 clearInterval(checkInterval); 54 }, 10000); 55}