Preloading images with JavaScript

后端 未结 14 1059
太阳男子
太阳男子 2020-11-22 03:17

Is the function I wrote below enough to preload images in most, if not all, browsers commonly used today?

function preloadImage(url)
{
    var img=new Image(         


        
14条回答
  •  长发绾君心
    2020-11-22 03:54

    const preloadImage = src => 
      new Promise(r => {
        const image = new Image()
        image.onload = r
        image.onerror = r
        image.src = src
      })
    
    
    // Preload an image
    await preloadImage('https://picsum.photos/100/100')
    
    // Preload a bunch of images in parallel 
    await Promise.all(images.map(x => preloadImage(x.src)))
    

提交回复
热议问题