递次加载图片要领

一般图片加载

//一般图片加载
var imglist = ['https://avatars3.githubusercontent.com/u/34082804?s=460&v=4','./img/2.jpg','https://avatars3.githubusercontent.com/u/34082804?s=460&v=4','https://github.githubassets.com/images/search-key-slash.svg','./img/2.jpg','https://avatars3.githubusercontent.com/u/34082804?s=460&v=4'];
loadImg(imglist);

function loadImg(imglist){
    var imgarr = [];
    var curimg = 0;
    var body = document.getElementsByTagName('body');

    for(var i =0;i<imglist.length;i++){
        
        var img = new Image();
        img.src = imglist[i];
        img.style.width = '200px';
        img.id = i;
        img.onload = function(){
            console.log('show    '+this.id)
        }
        imgarr.push(img);
        body[0].appendChild(img);
    }
}

递次加载图片要领1

//递次加载图片要领1、
function loadImg(imglist){
    var imgarr = [];
    var curimg = 0;
    var body = document.getElementsByTagName('body');

    for(var i =0;i<imglist.length;i++){
        
        var img = new Image();
        img.src = imglist[i];
        img.style.width = '200px';
        img.onload = function(){
            curimg +=1;
            if(curimg < imgarr.length){
                body[0].appendChild(imgarr[curimg]);
                console.log('show    '+curimg)
            }
            
        }
        imgarr.push(img);
    }
    body[0].appendChild(imgarr[0]);
}

promise要领


//promise要领

var imglist = ['https://avatars3.githubusercontent.com/u/34082804?s=460&v=4','./img/2.jpg','https://avatars3.githubusercontent.com/u/34082804?s=460&v=4','https://github.githubassets.com/images/search-key-slash.svg','./img/2.jpg','https://avatars3.githubusercontent.com/u/34082804?s=460&v=4'];

var body = document.getElementsByTagName('body');

function loadimg(i){
    var img = new Image();
    img.src = imglist[i];
    img.style.width = '200px';
    img.id = i;
    body[0].appendChild(img);
    return new Promise(function(resolve,reject){
                img.onload = function(){
                    console.log('show    '+this.id)
                    resolve(i+1)
                };
            })
}

var a = Promise.resolve(0);

var i=0;
while(i<imglist.length-1){
    a = a.then(function(i){
    console.log('load    '+i)
        return loadimg(i)
    });
    i++;
}

async 要领

//async 要领
async function loadImages(imglist){
    for(var i =0; i<imglist.length; i++){
        console.log('load    '+i)
        await loadImg(i); //实行完成以后才走下一步;
        console.log('finish   '+i);
    }
}

async function loadImg(i){
    var img = new Image();
    img.src = imglist[i];
    img.style.width = '200px';
    img.id = i;
    body[0].appendChild(img);
    return new Promise(function(resolve,reject){
        img.onload = function(){
            console.log('show    '+this.id)
            resolve(i+1);
        }
    })
}
    原文作者:yuan_yuanxu
    原文地址: https://segmentfault.com/a/1190000018350999
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞