Skip to content

Instantly share code, notes, and snippets.

@AndrewIngram
Last active January 15, 2024 17:50
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save AndrewIngram/b7e2b6ddea0b0d55bc7ed44a227d9311 to your computer and use it in GitHub Desktop.
Save AndrewIngram/b7e2b6ddea0b0d55bc7ed44a227d9311 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