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 visib
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. This example is written in TypeScript.
If its only about delivering few small "icons" - (why not using fonts?) - and if the server serves files gzipped you could use base64 for example.
Otherwise if the select is not instantly visible you could also add img tags (with display: none
) to the previous HTML. Another way would be to append Image objects to the DOM and wait for .onload
before displaying the component (this approach is used by the libraries you mentioned).
As far as I can imagine webpack or react can't do anything special for you here. This is something on client side and these are just the tools to implement your own preloading API (or even use the existing APIs in JS/TS, React, Angular, ......)
Well my friend, you have some options with link rel preload /prefetch and webpack lazyloading chunks.
more information :
https://github.com/GoogleChromeLabs/preload-webpack-plugin
The important thing to do is to save the image variable as PERSISTANT.
In a persistant context,in a global var or in a component that will not be unmounted before display the images :
window.preloadedPictures = []
In my component :
var preloadedData = pictures.map((picture) => {
const img = new Image();
img.src = picture.fileName;
return img
});
myContextOrGlobalVar.preloadedPictures = preloadedData ///IMPORTANT
If you have some images still reloading after being cached, try to store them in the window
object :
componentDidMount() {
const imagesPreload = [image1, image2, image3];
imagesPreload.forEach((image) => {
const newImage = new Image();
newImage.src = image;
window[image] = newImage;
});
}
(you don't need to call images from the window
object)
This works:
import im1 from 'img/im1.png'
import im2 from 'img/im2.png'
import im3 from 'img/im3.png'
componentDidMount() {
imageList = [im1, im2, im3]
imageList.forEach((image) => {
new Image().src = image
});
}