how to make sure images load sequentially

前端 未结 2 1966
名媛妹妹
名媛妹妹 2021-01-23 18:08

Here i have a simple test code which loads a test of images in browser.Here i used asynchronous onload event to add image to dom after it finishes loading. Images load just fine

2条回答
  •  暖寄归人
    2021-01-23 18:36

    You should wait for the callback from the onload event. If it's fired you can iterate and load the next image. This makes sure the images will be loaded in the right order (as in array).

    var images = [
        'http://d39kbiy71leyho.cloudfront.net/wp-content/uploads/2016/05/09170020/cats-politics-TN.jpg',
        'error',
        'https://s2.graphiq.com/sites/default/files/stories/t2/tiny_cat_12573_8950.jpg',
        'http://www.bharatint.com/img/categories/our-cat-shop-image.png'
    ], i = 0;
    
    function loadImageArrayAsync(){
        var image = new Image();
        image.onload = function(){
            document.body.appendChild(image);
            if (i++ < images.length - 1) loadImageArrayAsync();
        };
        image.onerror = function(){
            if (i++ < images.length - 1) loadImageArrayAsync();
         }
        image.src = images[i];
        image.style.height = '300px';
        image.style.width = '300px';
    }
    
    loadImageArrayAsync();
    

提交回复
热议问题