I am working on some code that will load a bunch (20+) of big images (~500 KB each) sequentially. After each image has loaded, it fades in. I used this fiddle from this discussion as a starting point.
I've got the images loading just the way I want, but I need to do a couple of other things without breaking this sequential loading. I need to load markup containing an iframe in between the third and fourth images, and I need to load a link after the images. Here is an example of the markup output I need:
<div id="container">
<img src="img-1.jpg" />
<img src="img-2.jpg" />
<img src="img-3.jpg" />
<div><iframe></iframe></div>
<img src="img-4.jpg" />
<img src="img-5.jpg" />
<img src="img-6.jpg" />
<img src="img-7.jpg" />
<img src="img-8.jpg" />
<img src="img-9.jpg" />
<a href="/link/">Link text</a>
</div>
I can load images just fine, but I am stuck with how to load that iframe only after the first three have loaded, and then have the rest of the images load, and then the link. Here is my current javascript:
var no = 22,
main = [],
i;
for (i = 1; i <= no; i++) {
main[i] = "path/to/image/folder/img-" + i + ".jpg";
}
function loadImages(arr,loc) {
if (arr.length === 0) {
return;
}
function imageLoaded(img) {
$(img).hide().appendTo(loc).fadeIn(800);
}
function loadImage() {
var url = arr.shift(),
img = new Image(),
timer;
img.src = url;
if (img.complete || img.readyState === 4) {
imageLoaded(img);
if (arr.length !== 0) {
loadImage();
}
}
else {
timer = setTimeout(function() {
if (arr.length !== 0) {
loadImage();
}
$(img).unbind("error load onreadystate");
}, 10000);
$(img).bind("error load onreadystatechange", function(e) {
clearTimeout(timer);
if (e.type !== "error") {
imageLoaded(img);
}
if (arr.length !== 0) {
loadImage();
}
});
}
}
loadImage();
}
loadImages(main,"#container");
The "no" variable sets the number of images to cycle through (I need to do this on multiple pages with different numbers of images), and the loadImages function takes arguments for which array to cycle through, and where to put the images. This code could probably be a lot cleaner, but I'm new to javascript. Any help would be greatly appreciated!