Skip to content Skip to sidebar Skip to footer

Preloaded Images Get Loaded Again

I'm preloading my images in componentDidMount like this: photos.forEach(picture => { const img = new Image(); img.src = picture.url; }); however when I try to insert my ima

Solution 1:

You can enable caching by the browser for the static resources like images/CSS/JS and other libraries such as jQuery etc which are not changed frequently. Try to add the cache-control response header for the static resources. These are the available values for cache control header.

Cache-Control: public 
Cache-Control: must-revalidate
Cache-Control: no-cache
Cache-Control: no-store
Cache-Control: no-transform
Cache-Control: private
Cache-Control: proxy-revalidate
Cache-Control: max-age=<seconds>
Cache-Control: s-maxage=<seconds>

You can also add the expires response header when these static resources are served. Setting the value to a previous date will make the browser not to cache the response.

Expires: <http-date>

Solution 2:

This is an expected behaviour. Why? when you do img.src = picture.url; there will be a Request for the image will happen. next time you are assigning an src to img tag again --> img src={photos[0].url} ,so the next Request will be triggered. (should be from disk cache this time).

let images = photos.map(picture => <img src={picture.src}/>);
then render this images variable like
ReactDOM.render(imgs, mountNode)


Post a Comment for "Preloaded Images Get Loaded Again"