预加载的图像会再次加载 [英] preloaded images get loaded again
问题描述
我正在这样将图像预加载到 componentDidMount
中:
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} ... />
它必须再次加载图像.然后,在网络"标签中,我有2个相同请求,来自相同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
具有相同的标头(时间c除外)
with identical headers (except for the time ofc)
推荐答案
您可以通过浏览器启用对图像/CSS/JS之类的静态资源以及不经常更改的其他库(如jQuery等)的缓存.尝试添加静态资源的缓存控制响应标头.这些是缓存控制标头的可用值.
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>
这篇关于预加载的图像会再次加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!