Last active
January 15, 2024 17:50
-
-
Save AndrewIngram/b7e2b6ddea0b0d55bc7ed44a227d9311 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use client"; | |
import { cache, unstable_postpone } from "react"; | |
import { preload } from "react-dom"; | |
const loadImage = cache((src: string) => { | |
return new Promise<void>((resolve, reject) => { | |
const img = new Image(); | |
img.src = src; | |
if (img.complete) { | |
return resolve(); | |
} else { | |
img.onload = () => resolve(); | |
img.onerror = reject; | |
} | |
}); | |
}); | |
type Props = React.ComponentPropsWithoutRef<"img">; | |
export default async function SuspendableImage({ src, ...props }: Props) { | |
preload(src, {as: "image"}); | |
if (typeof window === "undefined") { | |
unstable_postpone("client only"); | |
} | |
await loadImage(src); | |
return <img src={src} {...props} />; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment