Using jQuery to sequentially load and fade in elements
<p>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 <a href="http://jsfiddle.net/aGnBS/14/" rel="nofollow">this fiddle</a> from <a href="https://forum.jquery.com/topic/sequential-loading-of-images" rel="nofollow">this discussion</a> as a starting point.</p>

<p>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:</p>

<pre><code>&lt;div id="container"&gt;
  &lt;img src="img-1.jpg" /&gt;
  &lt;img src="img-2.jpg" /&gt;
  &lt;img src="img-3.jpg" /&gt;
  &lt;div&gt;&lt;iframe&gt;&lt;/iframe&gt;&lt;/div&gt;
  &lt;img src="img-4.jpg" /&gt;
  &lt;img src="img-5.jpg" /&gt;
  &lt;img src="img-6.jpg" /&gt;
  &lt;img src="img-7.jpg" /&gt;
  &lt;img src="img-8.jpg" /&gt;
  &lt;img src="img-9.jpg" /&gt;
  &lt;a href="/link/"&gt;Link text&lt;/a&gt;
&lt;/div&gt;
</code></pre>

<p>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:</p>

<pre><code>var no = 22,
main = [],
i;

for (i = 1; i &lt;= 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");
</code></pre>

<p>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!</p>
