如何确保图像顺序加载 [英] how to make sure images load sequentially

查看:115
本文介绍了如何确保图像顺序加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我有一个简单的测试代码,可以在浏览器中加载图像测试。这里我使用异步onload事件在完成加载后将图像添加到dom。图像加载得很好。问题是如果我连续重新加载页面多次图像序列更改。如果在图像1之前加载图像2,有时图像3首先加载,等等。我如何制作确保图像按顺序加载,比如第一次加载image1,然后是每次加载页面时的image2,image3等。我能做到这一点吗?

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.Problem is if i continuously reload the page multiple time image sequence change.As if image-2 loaded before image-1 ,sometimes image-3 loads first, etc.How i can make sure images load sequentially, like first load image1,then image2,image3 etc every time i load the page.How i can do that?

var images = ['cat1.png','cat2.jpg','cat3.jpg'];

var i = 0;
images.forEach(function(elem,index,arr){
   var image=new Image();
   image.onload = function(){
       document.body.appendChild(image);
       console.log(++i);
   };
   image.onerror = function(){
       console.log('error occured');

   } 
   image.src = elem;
   image.style.width = '300px';
   image.style.height = '300px';
});

推荐答案

您应该等待 onload 事件中的回调
如果已解雇,您可以迭代并加载下一张图片。
这样可确保以正确的顺序加载图像(如数组)。

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();

这篇关于如何确保图像顺序加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆