Skip to content

Commit

Permalink
v1.0.1 Refactored image lazy loading to use IntersectionObserver (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
lancegliser authored Dec 10, 2023
1 parent ac16c02 commit 8b7dd5e
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 23 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "netflix-react-apollo",
"version": "1.0.0",
"version": "1.0.1",
"private": true,
"scripts": {
"start": "vite --host 127.0.0.1 --port 3000",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
FunctionComponent,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useReducer,
useState,
Expand Down Expand Up @@ -63,31 +63,46 @@ const CompactSuggestionController: FunctionComponent<
fetchPolicy: "no-cache",
});

useEffect(() => {
if (!props.id) {
return;
}
if (props.displayImageUrl) {
return;
}
const intersectionObserver = useMemo(
() =>
new IntersectionObserver(
(entries, observer) => {
if (!entries.at(0)?.isIntersecting) {
return;
}
observer.disconnect();

const exec = () =>
getNodeDisplayImage({
variables: {
id: props.id!,
if (
// Already included, skip it
props.displayImageUrl ||
// Nothing to request, skip it
!props.id
) {
return;
}

getNodeDisplayImage({
variables: { id: props.id! },
});
},
});
{
rootMargin: "-30px 0px 0px -30px",
threshold: 0.02,
},
),

if (!lazy) {
exec();
[getNodeDisplayImage, props.displayImageUrl, props.id],
);
useLayoutEffect(() => {
if (!element) {
return;
}

// To save someone the trouble later. I attempted to use IntersectionObserver to load on demand.
// I was defeated by some interaction with the flicking.js library's carousel. All of them
// reported threshold 1 at all times.
requestIdleCallback(exec);
}, [getNodeDisplayImage, lazy, props.displayImageUrl, props.id]);
intersectionObserver.observe(element);
return () => {
intersectionObserver.disconnect();
};
}, [intersectionObserver, element]);

// Loads the extended node information to support the focused view
const [getItem, itemQuery] = useContentItemLazyQuery();
Expand Down

0 comments on commit 8b7dd5e

Please sign in to comment.