Next.js Discord

Discord Forum

Prefetching Images on other pages?

Unanswered
Lord_TCG#9068 posted this in #help-forum
Open in Discord
I created a payloadCMS app where I house my media content. Each page has an image covering the hero section, which is fetched onLoad, displaying skeleton content until it's ready.
import { useState } from "react";
import Image from "next/image";
import getHero from "@/hooks/getHero";
import styles from "./styles.module.css";

const SkeletonHero = ({ pageName }) => {
  const hero = getHero(pageName);
  // const hero = false;
  const [loaded, setLoaded] = useState(false);

  const url = process.env.NEXT_PUBLIC_CMS_URL_BASE;

  const handleImageLoad = () => {
    setLoaded(true);
  };

  return (
    <div className={styles.skeletonWrapper}>
      <aside
        className={`${styles.skeletonHero} ${loaded ? styles.fadeOut : ""}`}
      ></aside>
      {hero && (
        <Image
          onLoad={handleImageLoad}
          src={`${url}${hero?.fileName.url}`}
          alt={hero?.fileName.altText}
          width={1920}
          height={1080}
          style={{
            opacity: loaded ? 1 : 0,
            transition: "opacity 250ms ease-in-out",
          }}
        />
      )}
    </div>
  );
};

export default SkeletonHero;

This works well, except that it's fetched every time and never cached. I created this skeleton to be used in case of a slow connection, not to be displayed at all times. How can I instead prefetch all the images for the other pages, and only use the skeleton if needed, not every time?

0 Replies