jQuery load images in varying levels of quality
<p>I have a load of images that I am displaying on a website.</p>

<p>I have each image in varying levels of quality. I have thumb(~10kb), small(~200kb), medium(~1.2mb) and large(~2.5mb). What I would like would be for the thumb image to be displayed and then have javascript load the small and replace it when it has loaded, then load the medium and replace that and so on. That way an image pops up straight away and just gets better and better quality.</p>

<p>The image is being displayed as the background of a div and the size is set as contain so it will stretch the smaller images to fill the space.</p>

<p>All I need to some jQuery which will load the image and when loaded replace the background.</p>

<p><strong>UPDATE</strong></p>

<p>This is how I've solved it. I've created hidden img element which loads each image and then displays when done. But I wouldn't say no to some help cleaning it up.</p>

<p>The html is just</p>

<pre><code>&lt;img id="image_loader" style="display:none;" /&gt;
</code></pre>

<p>And the jQuery is</p>

<pre><code>$("#image_loader").attr("src", SmallURL);
$("#image_loader").load(function() {

    $("#image_container").css("background-image", 'url('+SmallURL+')');

    $("#image_loader").attr("src", MedURL);
    $("#image_loader").load(function() {

       $("#image_container").css("background-image", 'url('+MedURL+')');

       $("#image_loader").attr("src", LargeURL);
       $("#image_loader").load(function() {

           $("#image_container").css("background-image", 'url('+LargeURL+')');
           $("#image_loader").unbind('load');

       });
    });
});
</code></pre>

<p>But this is horribly messy. I've tried putting the URLs in an array and doing a <code>$.each</code> but it just skips to the large.</p>

<p><strong>SECOND UPDATE</strong></p>

<p>I've also found that I needed to unbind the load function once all images had been loaded or it would get stuck in an infinite loop. Hopefully if this can be cleaned up it can be done in a way which won't introduce any infinite loops.</p>

<p>Any ideas on how I can neaten this up?</p>
