我在 componentDidMount
中预加载我的图像,如下所示:
photos.forEach(picture => {
const img = new Image();
img.src = picture.url;
});
但是当我尝试像这样插入我的图像时(在另一个组件中)
<img src={photos[0].url} ... />
它必须重新加载图像。在我的网络选项卡中,我有 2 个相同的请求来自相同的 URL 相同的图像
具有相同的标题(除了时间 ofc)
最佳答案
您可以通过浏览器为图像/CSS/JS 和其他不经常更改的库(例如 jQuery 等)启用缓存。尝试为静态资源添加缓存控制响应头。这些是 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>
您还可以在提供这些静态资源时添加expires 响应 header 。将该值设置为以前的日期将使浏览器不缓存响应。
Expires: <http-date>
关于javascript - 预加载的图像再次加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55473008/