1const IMAGE_SELECTOR = "figure a img"; 2const CLASS_NAME = "image-is-smaller-than-container"; 3 4const getContainerWidth = (img) => { 5 const container = img.closest("figure") || img.parentElement; 6 if (!container) { 7 return null; 8 } 9 return container.getBoundingClientRect().width; 10}; 11 12const getIntrinsicImageWidth = (img) => { 13 if (img.naturalWidth) { 14 return img.naturalWidth; 15 } 16 return img.getBoundingClientRect().width; 17}; 18 19const updateImageClass = (img) => { 20 const containerWidth = getContainerWidth(img); 21 const intrinsicWidth = getIntrinsicImageWidth(img); 22 23 if (!containerWidth || !intrinsicWidth) { 24 return; 25 } 26 27 if (intrinsicWidth < containerWidth) { 28 img.classList.add(CLASS_NAME); 29 } else { 30 img.classList.remove(CLASS_NAME); 31 } 32}; 33 34const watchImage = (img) => { 35 if (img.complete) { 36 updateImageClass(img); 37 } else { 38 img.addEventListener( 39 "load", 40 () => { 41 updateImageClass(img); 42 }, 43 { once: true } 44 ); 45 } 46}; 47 48const handleResizeFactory = (images) => { 49 let rafId = null; 50 51 return () => { 52 if (rafId) { 53 return; 54 } 55 56 rafId = window.requestAnimationFrame(() => { 57 images.forEach(updateImageClass); 58 rafId = null; 59 }); 60 }; 61}; 62 63const initImageSizeWatcher = () => { 64 if (typeof window === "undefined" || typeof document === "undefined") { 65 return; 66 } 67 68 const images = document.querySelectorAll(IMAGE_SELECTOR); 69 if (!images.length) { 70 return; 71 } 72 73 images.forEach((img) => { 74 watchImage(img); 75 }); 76 77 const handleResize = handleResizeFactory(images); 78 window.addEventListener("resize", handleResize); 79}; 80 81export default initImageSizeWatcher;
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.