Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I wrote a web cam viewer where the javascript source basically sources the image according to an "active" class in a list.

I was wondering what are good modern techniques to make images load faster in the background, so a user can get a better experience flicking through images.

Obviously it doesn't make sense to download all images, I imagine it needs to be like when one scrolls through a Google map in principle, images are loaded on demand.

share|improve this question

migrated from Jan 11 '12 at 22:41

This question came from our site for peer programmer code reviews.

up vote 2 down vote accepted

I haven't really looked into this specific technique before, but this is how I'd approach it:

$(function() {
    var src = [
    var loaded = [];
    var idx = 0;

    var sz = src.length;
    for(var n = 0; n < sz; ++n) {
        var img = new Image();
        img.onload = function() {
            if(sz === loaded.length) onLoaded();
        img.src = src[n];

    function onLoaded() {

    $("#next").click(function(e) {
        if(!$(this).hasClass("disabled")) {
            idx = (idx + 1) % sz;


In my fiddle sample, I only force the client to load the first image with the rest of the page. Then, on jQuery load ($(function() {})), I cache all other images I want to display with the script (3 images in this case).

Once each image has loaded, I push it into a cached array and check if the cached size equals the source size. If it does, then I call onLoaded.

One optimization to this might be to simply use the cache the image on the page rather than load another one (0th element in src).

Of course, this can easily be done with native Javascript as well, I chose to use jQuery for this example for no real good reason ;).

share|improve this answer
Thanks for your input. Since rewritten the code like so: where I just load the next next image. Performance is good enough for me! – hendry Jan 22 '12 at 9:08

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.