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';
});
Here is another approach. It fires off all the image requests in a loop, then when a response is received it does a bit of processing to work out which images can be displayed. This way you don't have to wait for one image to finish loading before requesting the next. The code could probably do with tidying up but you get the idea...
Sample output:
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).