Skip to content

Instantly share code, notes, and snippets.

@revskill10
Forked from AndrewIngram/SuspendableImage.tsx
Created October 30, 2023 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save revskill10/fa605b1908a80fb19a5126ae4e318a7b to your computer and use it in GitHub Desktop.
Save revskill10/fa605b1908a80fb19a5126ae4e318a7b to your computer and use it in GitHub Desktop.
"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