|
1 | 1 | 'use client'; |
2 | 2 |
|
3 | 3 | import Link from 'next/link'; |
4 | | -import { useState, useCallback } from 'react'; |
| 4 | +import { useRouter } from 'next/navigation'; |
| 5 | +import { useState } from 'react'; |
| 6 | + |
| 7 | +const loadedImages = new Set<string>(); |
5 | 8 |
|
6 | 9 | interface PrefetchLinkProps extends React.ComponentProps<typeof Link> { |
7 | 10 | href: string; |
| 11 | + preFetchImages: string[]; |
8 | 12 | } |
9 | 13 |
|
10 | | -export const PrefetchLink: React.FC<PrefetchLinkProps> = ({ href, children, ...props }) => { |
11 | | - const [prefetch, setPrefetch] = useState(false); |
12 | | - |
13 | | - const handleMouseEnter = useCallback(() => { |
14 | | - setPrefetch(true); |
15 | | - }, []); |
| 14 | +export const PrefetchLink: React.FC<PrefetchLinkProps> = ({ |
| 15 | + href, |
| 16 | + preFetchImages, |
| 17 | + children, |
| 18 | + ...props |
| 19 | +}) => { |
| 20 | + const [preloading, setPreloading] = useState<(() => void)[]>([]); |
| 21 | + const router = useRouter(); |
16 | 22 |
|
17 | 23 | return ( |
18 | | - <Link href={href} prefetch={prefetch} onMouseEnter={handleMouseEnter} {...props}> |
| 24 | + <Link |
| 25 | + href={href} |
| 26 | + prefetch={false} |
| 27 | + onMouseEnter={() => { |
| 28 | + router.prefetch(href); |
| 29 | + if (!preFetchImages || preFetchImages.length < 1) return; |
| 30 | + |
| 31 | + const p: (() => void)[] = []; |
| 32 | + |
| 33 | + for (const image of preFetchImages) { |
| 34 | + const remove = prefetchImage(image); |
| 35 | + if (remove) p.push(remove); |
| 36 | + } |
| 37 | + |
| 38 | + setPreloading(p); |
| 39 | + }} |
| 40 | + onMouseLeave={() => { |
| 41 | + for (const remove of preloading) { |
| 42 | + remove(); |
| 43 | + } |
| 44 | + |
| 45 | + setPreloading([]); |
| 46 | + }} |
| 47 | + {...props} |
| 48 | + > |
19 | 49 | {children} |
20 | 50 | </Link> |
21 | 51 | ); |
22 | 52 | }; |
| 53 | + |
| 54 | +function prefetchImage(image: string) { |
| 55 | + if (loadedImages.has(image)) return; |
| 56 | + |
| 57 | + const img = new Image(); |
| 58 | + img.decoding = 'async'; |
| 59 | + img.fetchPriority = 'low'; |
| 60 | + img.src = image; |
| 61 | + |
| 62 | + let done = false; |
| 63 | + |
| 64 | + img.onload = img.onerror = () => { |
| 65 | + done = true; |
| 66 | + loadedImages.add(image); |
| 67 | + }; |
| 68 | + |
| 69 | + return () => { |
| 70 | + if (done) return; |
| 71 | + img.src = ''; |
| 72 | + }; |
| 73 | +} |
0 commit comments