diff options
author | Michael Hunteman <michael@huntm.net> | 2024-11-01 14:10:11 -0700 |
---|---|---|
committer | Michael Hunteman <michael@huntm.net> | 2024-11-01 14:10:11 -0700 |
commit | fab698d676d43a46b0fd5df592915ca12111dbcb (patch) | |
tree | 0106ff4ac6583f0761b43474939fd2db0fbf0f76 /client/src/useBlurryLoad.ts | |
parent | 59d6e1c7470b8f544dc128825ea5ff55ac34b992 (diff) |
Blurry load
Diffstat (limited to 'client/src/useBlurryLoad.ts')
-rw-r--r-- | client/src/useBlurryLoad.ts | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/client/src/useBlurryLoad.ts b/client/src/useBlurryLoad.ts new file mode 100644 index 0000000..59069d2 --- /dev/null +++ b/client/src/useBlurryLoad.ts @@ -0,0 +1,38 @@ +import { useEffect } from 'react'; +import './blurry-load.css'; + +export interface UseBlurryLoadProps { + toBlurImages?: Element[]; +} + +export const useBlurryLoad = (props?: UseBlurryLoadProps) => { + const { toBlurImages = [] } = props ?? {}; + + useEffect(() => { + const images: Element[] = [...toBlurImages]; + if (toBlurImages.length === 0) { + images.push(...document.querySelectorAll('.blurry-load')); + } + + const lazyImageObserver = new IntersectionObserver(function (entries) { + entries.forEach(function (entry) { + if (!entry.isIntersecting) return; + + const image = entry.target; + const currentImage = new Image(); + currentImage.setAttribute( + 'src', + image.getAttribute('data-large') ?? '' + ); + + currentImage.onload = () => { + image.setAttribute('src', currentImage.src); + image.classList.add('blur-out'); + }; + lazyImageObserver.unobserve(image); + }); + }); + + images.forEach((img) => lazyImageObserver.observe(img)); + }, [toBlurImages]); +}; |