#How to preload a list of images in next.js?

18 messages · Page 1 of 1 (latest)

dawn wadiBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

high linden
#

You can preload an image with new Image() (native web API)

new Image().src = url;

Notice that the cache will be released if you're no longer displaying the image after few seconds
Hence, the amount of preloaded images is still limited

paper parcel
#

A dirty way to ensure the image is not cleared from cache: manually fetch the image with JavaScript then use it to construct a data URL

elfin cape
elfin cape
paper parcel
elfin cape
#

would this work if i'm getting images from the public folder for example?

paper parcel
#

yes src can be any image URLs, /your/image.png or https://external.site.com/image.png both work

#

normally the img tag handles the fetching, what i did here is essentially handle the fetching myself manually instead of having the img tag do it

high linden
#

The built-in <image /> component won't preload all the images unless they're mounted. The method mentioned by joulev or me will be better for that

elfin cape
elfin cape
#

appreciate the help y'all :3

dawn wadiBOT
#
✅ Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer
#
✅ Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer

[Click here](#1139427594245259284 message)

elfin cape
#

Hi sorry to bother you guys again, it looks like the images are preloading in the network tab but i'm not sure how to render the images in my jsx

  useEffect(()=>{
    window.addEventListener('scroll', scrollProgress);

    const preloadImages = () => {
      const emptyArray = [...Array(frameCount+1).keys()]

      const imageArray = emptyArray.map((element)=>{
        const img = new Image();
        img.src = `/image-sequence/animation (${element}).png`
        img.alt = 'hi'
        return img;
      })
      setImages(imageArray)
    }

    preloadImages();
    return () => window.removeEventListener('scroll', scrollProgress)
  },[])
#

I tried this but it didn't work

const [images, setImages] = useState([])
...
...
...
 {images[frame]}