preloaded images get loaded again

删除回忆录丶 提交于 2021-01-28 02:51:12

问题


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

with identical headers (except for the time ofc)


回答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>



回答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)



来源:https://stackoverflow.com/questions/55473008/preloaded-images-get-loaded-again

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!