Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preload images in React.js?

How to preload images in React.js? I have dropdown select component which works like menu , but i have to preload image icons for items,because sometimes they are not visible on first open.

I have tried:

https://github.com/sambernard/react-preload

https://github.com/wizardzloy/react-img-preload

First one has nice API easy to understand and use ,but is spaming console with warning that images were not loaded even when they were. Second one has strange API ,but I tried example and it did not preload anything.

So I probably need to implement something at my own ,but do not know where to start. Or another possibility would be to loaded them with webpack.

like image 639
Ľubomír Avatar asked Mar 05 '17 23:03

Ľubomír


People also ask

How do you preload assets in React?

To preload images with React and JavaScript, we can create our own hook. import { useEffect } from "react"; export const usePreloadImages = (imageSrcs) => { useEffect(() => { const randomStr = Math. random().

Can we preload images?

To preload responsive images, new attributes were recently added to the <link> element: imagesrcset and imagesizes . They are used with <link rel="preload"> and match the srcset and sizes syntax used in <img> element. This kicks off a request using the same resource selection logic that srcset and sizes will apply.

How do you load all images before showing the page in React?

You can ensure that an image is pre-downloaded 100% well before it gets displayed to the screen. Simply create an Image element and set its src property to the URL where the image is located. Then use the image's onload event to detect when it is ready for instant display.


1 Answers

Supposing you have pictures: string[]; - array of pictures urls defined in your component's props. You should define componentDidMount() method in your component and then just create new Image object for each picture you want to be preloaded:

componentDidMount() {     this.props.pictures.forEach((picture) => {         const img = new Image();         img.src = picture.fileName;     }); } 

It forces browser to load all images.

like image 67
Lulchenko Aleksey Avatar answered Sep 29 '22 04:09

Lulchenko Aleksey