我应该如何在反应中实现图像的延迟加载?

wil*_*ney 16 lazy-loading reactjs

我正在尝试向我的 React 应用程序添加延迟加载,因为我有 200 多个在初始加载时不需要的图像。如果我延迟加载图像,这是否意味着直到屏幕上需要它们时才会加载它们?

我目前正在将 4 组约 50 个图像导入到 .js 文件中,然后将它们添加到对象中,以便它们可以在我的组件中动态使用。看起来像这样...

// SportImages.js file
import Football from './images/football.png
import Cricket from './images/cricket.png
import Soccer from './images/soccer.png
... // another 50 or so imports

export default {
  Football,
  Cricket,
  Soccer,
  ... // another 50 or so files
}

// and then in my component
cards.map(x => {
  return (
    <img src={SportImages[x.image_ref]} />
  )
})
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,如果我想延迟加载每个图像,我应该在组件文件或主图像文件中使用延迟加载吗?

Jon*_*ops 27

您可以将该loading属性添加到图像元素以延迟加载图像。有关此属性的完整解释指南可以在web.dev上找到。

在您的情况下,它可能如下所示:

cards.map(card => (
  <img src={SportImages[card.image_ref]} loading="lazy" />
))
Run Code Online (Sandbox Code Playgroud)

您还应该确保指定widthheight属性,以便浏览器可以将元素以正确的尺寸放置在页面上。

  • IOS 上的 Safari 目前不支持 `loading=lazy`:https://caniuse.com/?search=loading (4认同)
  • Safari 现在也支持延迟加载 https://webkit.org/blog/12445/new-webkit-features-in-safari-15-4/ (2认同)