Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 images like this (in another component)

<img src={photos[0].url} ... />

it has to load the image again. In my network tab, I then have 2 identical requests for the same image from the same URL

identical images

with identical headers (except for the time ofc)

image header (identical for both images)

like image 584
cubefox Avatar asked Oct 19 '25 22:10

cubefox


1 Answers

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>
like image 62
Rahul Malu Avatar answered Oct 22 '25 12:10

Rahul Malu