mirror of
https://github.com/aljazceru/rabbit.git
synced 2025-12-18 06:24:25 +01:00
46 lines
1.1 KiB
TypeScript
46 lines
1.1 KiB
TypeScript
import { Component, JSX, Show, createSignal, onCleanup, onMount } from 'solid-js';
|
|
|
|
export type LazyLoadProps = {
|
|
threshold?: number[] | number;
|
|
fallback?: JSX.Element;
|
|
children: () => JSX.Element;
|
|
};
|
|
|
|
const LazyLoad: Component<LazyLoadProps> = (props) => {
|
|
let containerRef: HTMLDivElement | undefined;
|
|
|
|
const [visible, setVisible] = createSignal<boolean>(false);
|
|
|
|
onMount(() => {
|
|
const observer = new IntersectionObserver(
|
|
(entries) => {
|
|
entries.forEach((entry) => {
|
|
if (entry.isIntersecting) {
|
|
setVisible(true);
|
|
observer.disconnect();
|
|
}
|
|
});
|
|
},
|
|
{
|
|
threshold: props.threshold ?? 0,
|
|
},
|
|
);
|
|
if (containerRef != null) {
|
|
observer.observe(containerRef);
|
|
}
|
|
|
|
onCleanup(() => {
|
|
observer.disconnect();
|
|
});
|
|
});
|
|
|
|
return (
|
|
<Show when={visible()} fallback={<div ref={containerRef}>{props.fallback}</div>} keyed>
|
|
{/* eslint-disable-next-line @typescript-eslint/no-unused-vars */}
|
|
{(_) => props.children()}
|
|
</Show>
|
|
);
|
|
};
|
|
|
|
export default LazyLoad;
|