From cab4cf886732c48bb5eebbd3db3456277d6281f4 Mon Sep 17 00:00:00 2001 From: Malte Ubl Date: Mon, 21 Oct 2024 08:11:29 -0700 Subject: [PATCH 1/3] Eager image prefetch for search --- src/components/ui/link.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/components/ui/link.tsx b/src/components/ui/link.tsx index 71bb9fe..62e489f 100644 --- a/src/components/ui/link.tsx +++ b/src/components/ui/link.tsx @@ -20,8 +20,6 @@ async function prefetchImages(href: string) { if (!href.startsWith("/products")) { return []; } - // Delay the prefetch until after Next.js has time to prefetch the page itself. - await sleep(1000); const url = new URL(href, window.location.href); const imageResponse = await fetch(`/api/prefetch-images${url.pathname}`, { priority: "low", From c7fe161a120a80e230aa331e2ad20c2ff669cf3e Mon Sep 17 00:00:00 2001 From: Malte Ubl Date: Mon, 21 Oct 2024 08:16:28 -0700 Subject: [PATCH 2/3] Handle prefetch in user code to have proper ordering --- src/components/ui/link.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/components/ui/link.tsx b/src/components/ui/link.tsx index 62e489f..f58e1ef 100644 --- a/src/components/ui/link.tsx +++ b/src/components/ui/link.tsx @@ -53,7 +53,9 @@ export const Link: typeof NextLink = (({ children, ...props }) => { const entry = entries[0]; if (entry.isIntersecting) { // Set a timeout to trigger prefetch after 1 second - prefetchTimeout = setTimeout(() => { + prefetchTimeout = setTimeout(async () => { + router.prefetch(String(props.href)); + await sleep(0); // We want the doc prefetches to happen first. void prefetchImages(String(props.href)).then((images) => { setImages(images); }, console.error); @@ -82,7 +84,9 @@ export const Link: typeof NextLink = (({ children, ...props }) => { return ( { + router.prefetch(String(props.href)); for (const image of images) { if (image.loading === "lazy" || seen.has(image.srcset)) { continue; From 4c627d5d6e719c7b6362db587018b08b65aa88f3 Mon Sep 17 00:00:00 2001 From: Malte Ubl Date: Mon, 21 Oct 2024 08:22:33 -0700 Subject: [PATCH 3/3] fix-prefetch --- src/components/ui/link.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/ui/link.tsx b/src/components/ui/link.tsx index f58e1ef..22fcafe 100644 --- a/src/components/ui/link.tsx +++ b/src/components/ui/link.tsx @@ -17,7 +17,7 @@ function sleep(ms: number) { } async function prefetchImages(href: string) { - if (!href.startsWith("/products")) { + if (!href.startsWith("/") || href.startsWith("/order")) { return []; } const url = new URL(href, window.location.href);