10

I want to show a skeleton while my image is loading. I tried to pass an onLoad prop in the new Image component provided by NextJS but the function fires off before the image is loaded.

Here is my code

const [loaded, setLoaded] = useState(false);

<Image
  src={src}
  alt={""}
  className={styles.image_tag}
  onLoad={(e) => setLoaded(true)}
  style={{ opacity: loaded ? "1" : "0" }}
  layout={"fill"}
/>

{!loaded && (
  <Skeleton
    className={styles.skeleton}
    variant={"rect"}
    animation={"wave"}
  />
)}
2
  • Image should displayed only when loaded is true. Its displaying always in your code Commented Jan 20, 2021 at 16:00
  • Is there any way that I can optimize images in the <img> tag Commented Jan 21, 2021 at 4:29

2 Answers 2

6

As of 11.1 you can use onLoadingComplete

A callback function that is invoked once the image is completely loaded and the placeholder has been removed.

https://nextjs.org/docs/api-reference/next/image#onloadingcomplete

Sign up to request clarification or add additional context in comments.

3 Comments

For me this fires immediately when emulating slow connection speed
Have you disabled your cache?
I refreshed the page using Ctrl + Shift + R, which forces the browser to refresh without caching. To my understanding that should suffice
5

You could can use the onLoad prop like so:

Referenced from https://github.com/vercel/next.js/discussions/20155

const [isImageReady, setIsImageReady] = useState(false);

const onLoadCallBack = (e)=>{
   setIsImageReady(true)
   typeof onLoad === "function" && onLoad(e)
}

return(
  <div>
   {!isImageReady && 'loading image...'}
   <Image 
     onLoad={onLoadCallBack} 
     src={'/'+image} 
     alt={title} 
     width={260}  
     height={160} />
  </div>
)

******************************* UPDATE *****************************

Nextjs now provides a placeholer and blurDataURL prop with which you can show an image placeholder before the main image is loaded.

An example


<Image
 className="image"
 src={image.src}
 alt={image.alt}
 layout="fill"
 objectFit="cover"
 objectPosition="top center"
 placeholder="blur"
 blurDataURL="/images/blur.jpg"
/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.