javascript - 预加载的图像再次加载

标签 javascript html reactjs google-chrome

我在 componentDidMount 中预加载我的图像,如下所示:

photos.forEach(picture => {
  const img = new Image();
  img.src = picture.url;
});

但是当我尝试像这样插入我的图像时(在另一个组件中)

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

它必须重新加载图像。在我的网络选项卡中,我有 2 个相同的请求来自相同的 URL 相同的图像

identical images

具有相同的标题(除了时间 ofc)

image header (identical for both images)

最佳答案

您可以通过浏览器为图像/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/

相关文章:

JavaScript 运行时错误 : Unable to set property

javascript - jshint 函数名称中带点

jquery - SEO友好性是否胜过优雅?

javascript - IE,从打开的下拉列表中跳出胜过 knockoutjs 中的可见绑定(bind)

html - 无法将图像附加到 div

reactjs - 如何动态构建 Redux 表单?

javascript - javascript 减法问题

javascript - 从字符串中动态选择类 - "MyClassName"-> MyClassName

javascript - 当 redux 更改商店 Prop 时运行我的方法。响应式JS

reactjs - 如何防止用户返回 react-router-dom?