Skip to content

Commit da963cf

Browse files
committed
Lazy load merch nav products
1 parent 3d52b84 commit da963cf

1 file changed

Lines changed: 34 additions & 2 deletions

File tree

src/components/Navbar.tsx

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -999,10 +999,41 @@ function MerchMenuContent({
999999
onNavigate: () => void
10001000
variant: 'desktop' | 'mobile'
10011001
}) {
1002+
const rootRef = React.useRef<HTMLDivElement>(null)
1003+
const [shouldLoad, setShouldLoad] = React.useState(false)
10021004
const [products, setProducts] = React.useState<Array<ProductListItem>>([])
10031005
const [loading, setLoading] = React.useState(true)
10041006

10051007
React.useEffect(() => {
1008+
const root = rootRef.current
1009+
const triggerWrap =
1010+
variant === 'desktop'
1011+
? root?.closest<HTMLElement>('.ts-mega-trigger-wrap')
1012+
: null
1013+
const target = triggerWrap ?? root
1014+
1015+
if (!target) {
1016+
return
1017+
}
1018+
1019+
const load = () => {
1020+
setShouldLoad(true)
1021+
}
1022+
1023+
target.addEventListener('pointerenter', load)
1024+
target.addEventListener('focusin', load)
1025+
1026+
return () => {
1027+
target.removeEventListener('pointerenter', load)
1028+
target.removeEventListener('focusin', load)
1029+
}
1030+
}, [variant])
1031+
1032+
React.useEffect(() => {
1033+
if (!shouldLoad) {
1034+
return
1035+
}
1036+
10061037
let cancelled = false
10071038

10081039
async function loadProducts() {
@@ -1036,7 +1067,7 @@ function MerchMenuContent({
10361067
return () => {
10371068
cancelled = true
10381069
}
1039-
}, [])
1070+
}, [shouldLoad])
10401071

10411072
const allMerchItem: NavMenuItem = {
10421073
label: 'All Merch',
@@ -1047,6 +1078,7 @@ function MerchMenuContent({
10471078

10481079
return (
10491080
<div
1081+
ref={rootRef}
10501082
className={twMerge(variant === 'desktop' ? 'grid gap-4' : 'grid gap-3')}
10511083
>
10521084
<section>
@@ -1059,7 +1091,7 @@ function MerchMenuContent({
10591091
variant === 'desktop' && 'md:grid-cols-3',
10601092
)}
10611093
>
1062-
{loading
1094+
{shouldLoad && loading
10631095
? Array.from({ length: 3 }, (_, index) => (
10641096
<div
10651097
key={index}

0 commit comments

Comments
 (0)