你如何用react预加载背景img?

时间:2018-11-07 22:18:51

标签: javascript reactjs

我有一个APi,我从中提取数据,而图像以url的形式出现, 我已经做到了,这样当提取完成时,应用程序将呈现提要。 问题是图像在获取后加载。我如何坚持加载程序,直到图像加载完成?

1 个答案:

答案 0 :(得分:1)

您没有向我们显示任何代码,因此我们可以为您提供很多帮助,例如您正在使用哪些lib从api中获取内容。

但这是一种更通用的方式:

function loadEverything() {
  // get the api response
  const res = await fetch(url)
  const json = await res.json()

  // start loading all images
  let images = json.images.map(image => new Promise((rs, rj) => {
    const img = new Image()
    img.onload = () => rs(img)
    img.onerror = () => rj()
  }))

  // wait for everything to load
  images = await Promise.all(images)

  // now append everything to the DOM and remove the loader
}

意味着您必须添加dom元素,而不仅仅是将某些src属性绑定到url

ofc,还有其他解决方法。例如使用服务人员+自定义缓存存储。或隐藏DOM,直到一切完成