用promise做图片的预加载

var url='jsonp-master/0.jpg'
var url1='jsonp-master/1.jpg'
var url2='jsonp-master/2.jpg'
var img=document.createElement('img');
var img1=document.createElement('img');
var img2=document.createElement('img');
img.src=url;
img1.src=url1;
img2.src=url2;

function loading(img){
    return new Promise(function(resolve,reject){
        img.onload=function(){
            resolve(img)
        }
    })
}
//图片预加载  等所有图片都加载完毕后统一显示
Promise.all([
    loading(img),loading(img1),loading(img2)
]).then(function(res){
    for(var i=0;i<res.length;i++){
        document.body.appendChild(res[i])
    }
})
//谁加载的快就显示谁
Promise.race([
    loading(img),loading(img1),loading(img2)
]).then(function(res){
        document.body.appendChild(res)
})

  

原文地址:https://www.cnblogs.com/liuhao-web/p/7127671.html