correct strategy to preload image before mount? #76776
-
SummaryWhat is the ideal way to preload image before mounting the component that actually uses the image? Say I have a component as follow: import Image from "next/image";
import backgroundImage from "/../../public/common/admin-login-background.png"; // static import
export function LoginBackgroundImage() {
return (
<div className="bg-NS-1 tablet:flex relative hidden h-full w-full">
<Image
src={backgroundImage}
alt="admin-login-background"
className="object-cover"
sizes="100vw"
fill={true}
priority={true}
placeholder="blur"
fetchPriority="high"
/>
</div>
);
} Adding "priority" attribute to image preloads the resource when "LoginBackgroundImage" component mounts, <link preload ... /> being attached. There are some cases where I need to preload before mounting the component. I found ReactDOM.preload does the same thing without requiring the component to be mounted. // Some root level layout.tsx
export default function Layout() {
preload("/common/admin-login-background.png", { as: "image" })
} If either of one is available, should I use either of them or both can be used simultaneously? The reason for this question is that when "LoginBackgroundImage" mounts, nextjs seems to attach <link preload.... /> tag on the downstream tree while "ReactDOM.preload" attaches the the preload link to "<head />" tag. If I use ReactDOM.preload, should I remove "priority / fetchPriority" from the Image component? Additional informationOperating System:
Platform: darwin
Arch: arm64
Version: Darwin Kernel Version 24.3.0: Thu Jan 2 20:24:22 PST 2025; root:xnu-11215.81.4~3/RELEASE_ARM64_T6041
Available memory (MB): 49152
Available CPU cores: 12
Binaries:
Node: 22.14.0
npm: 10.9.2
Yarn: 1.22.22
pnpm: N/A
Relevant Packages:
next: 15.2.1 // Latest available version is detected (15.2.1).
eslint-config-next: 15.2.1
react: 19.0.0
react-dom: 19.0.0
typescript: 5.7.3
Next.js Config:
output: N/A ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I think, you have to see this first, through the "native" DOM utilities, you have at hand. The formal way to preload, as soon as possible, is through ReactDOM's preload, does that for you, so you kind of got your framework answer there.
|
Beta Was this translation helpful? Give feedback.
I think, you have to see this first, through the "native" DOM utilities, you have at hand. The formal way to preload, as soon as possible, is through
link
elements, withrel="preload"
, https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel/preload#what_types_of_content_can_be_preloadedReactDOM's preload, does that for you, so you kind of got your framework answer there.
fetchPriority
, is perhaps best modeled, when you think of several resources that are already in queue to be fetched, then you can hint at the browser that a given resource, should go ahead of the queue, everything else being equal.