blob: 59069d2f2f7718783055cfc452564b2df08eed02 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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]);
};
|