Shenglian / -WORK_TIP

工作上小技巧
4 stars 1 forks source link

[js] perloading images with Promise #176

Closed Shenglian closed 4 years ago

Shenglian commented 5 years ago
let source = [
  'imageUrl1',
  'imageUrl2',
  'imageUrl3',
]

preLoadingImages(source)
.then(res => console.log(res))
.catch(error => console.log(error))

function loadImage(url) {
  return new Promise((resolve, reject) => {
    let image = new Image()

    image.onload = () => resolve(image)
    image.onerror = reject
    image.src = url
  })
}

function preLoadingImages(source) {
  let pr = []

  source.forEach(url => {
    let image = 
      loadimage(url)
      .then(res => {})
      .catch(error => {})

    pr.push(image)      
  })

  return Promise.all(pr)
}