Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11523

Control which image loads first

I'm wondering if there is a way to control which image loads first when the user opens the website. The problem is that I have a simple one-page website that is taking too much time to open the first image (Big Home image - example). I would like to load this image first, and then load the other images in the website, should I do it manually with Jquery for each image (using $.attr("src") after document.ready)? or is there a better way?

Upvotes: 0

Views: 173

Answers (1)

Rajshekar Reddy
Rajshekar Reddy

Reputation: 18987

Control which image loads first

If you want to have control over which images to load first and load the images synchronously then try this. Working JsFiddle

var loaded = 0;
var imgSrcArray = ["https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/Small_icosihemidodecahedron.png/100px-Small_icosihemidodecahedron.png",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Small_cubicuboctahedron.png/100px-Small_cubicuboctahedron.png",
"https://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Small_dodecahemidodecahedron.png/100px-Small_dodecahemidodecahedron.png",
"https://upload.wikimedia.org/wikipedia/commons/thumb/a/ad/Small_rhombicuboctahedron.png/100px-Small_rhombicuboctahedron.png"];


$('div img').on('load',function(){
 loaded++;
 var indexOfThisImg = imgSrcArray.indexOf($(this).attr('src'));
 $('#output').append("loaded image " +indexOfThisImg + '<br/>');
 loadNextImg(loaded);
});

function loadNextImg(index){
   $('div img:eq('+index+')').attr('src',imgSrcArray[index]); 
   // if the imag tags are not continuous and you want to load the images in random position in an order then you can maintain the order of the images in a separate array and then use that indexes to load the images. 
}

$('div img:eq(0)').attr('src',imgSrcArray[0]); 
//trigger the load of first image, which starts the chain reaction   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img />
<img />
<img />
<img />
</div>
<div id="output">
  
</div>

The idea is to hold all the images src in an array and load the first image, and on the load event of the image increment the array index and load the second one and so on.. This way we have control on the order of the images that should load. let me know if this helps

Upvotes: 1

Related Questions