Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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 codereview.stackexchange.com Jan 11 '12 at 22:41

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

1 Answer 1

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 = [
        "https://developer.mozilla.org/skins/mdn/Transitional/img/mdn-logo-sm.png",
        "http://cdn.sstatic.net/programmers/img/logo.png?v=123",
        "http://livedocs.adobe.com/flex/3/html/images/adobe.png"
    ];
    var loaded = [];
    var idx = 0;

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

    function onLoaded() {
        $("#next").removeClass("disabled").addClass("enabled");
    }

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

            $($("img")[0]).remove();
            $("#container").append(loaded[idx]);
        }
    });
});

http://jsfiddle.net/dbrecht/6MLHR/

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: github.com/kaihendry/Praze/blob/master/main.js where I just load the next next image. Performance is good enough for me! –  hendry Jan 22 '12 at 9:08

Your Answer

 
discard

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.