Preloading set of images using jQuery
<p>I have a set of images that are frames in an animation like: <code>frame-1.jpg, frame-2.jpg</code> and I have about 400 images.</p>

<p>What I want to do is preload these 400 images before the animation starts.</p>

<p>Usually when preloading images I use the following:</p>

<pre><code>var images = [
        'img/nav-one-selected.png',
        'img/nav-two-selected.png',
        'img/nav-three-selected.png',
        'img/nav-four-selected.png'
    ];

    $(images).each(function() {
        var image = $('&lt;img /&gt;').attr('src', this);
    });
</code></pre>

<p>But in this instance, listing the images in the var isn't feasible, and I also wish to fire off the start animation once the images have all been loaded.</p>

<p>So far I have the following:</p>

<pre><code>$spinner_currentFrame = 1;
$numFrames = 400;

function preloadImages() {
    $($images).each(function() {
        var image = $('&lt;img /&gt;').attr('src', this);
    });
    startAnimation();
}

function startAnimation() {
    $spinner_loadingAnim = setInterval(function () {
        UpdateSpinner();
    }, 140);
}

function UpdateSpinner() {
    $spinner_currentFrame = $spinner_currentFrame + 1;
    if($spinner_currentFrame &gt; $numFrames) {
        $spinner_currentFrame = 1;
    }
    console.log($spinner_currentFrame);
    $('#spinner').css("background-image", "url(frame-" + $spinner_currentFrame + ".jpg)");
}

$(document).ready(function() {
    preloadImages();
});
</code></pre>

<p>So the plan is that I preload images that are from 1 to 400 and then once that's completed then start the animation. How would I build the $images var though?</p>

<p>I've thought about something like:</p>

<pre><code>$images = [];
$frame = 1;
$numFrames = 400;
$($frame).each(function() {

    $frame = $frame + 1;
    if($frame &lt;= $numFrames) {

     $images =+ 'frame-' + $frame + '.jpg';

    }

});
</code></pre>

<p>But I'm not sure how a) efficient this is and b) how to do the callback once all images have loaded successfully.</p>
