Preload Images Sequentially With jQuery

Blog Projects
javascript jquery
HEADS UP! This article was written in 2007. Information provided might not be valid anymore and should be taken with a grain of salt.

Here is a small code snippet I use for preloading images for mouseovers. It uses $(window).bind("load", function() { xxx }) to wait until all page elements have finished loading. This includes all images. If you use $(document).ready() it would start preloading images while other elements are still loading. This will make rest of the page feel slow.

Code below searches for all images with class hover. Then it adds _on to image name and pushes it to preload queue. When page has finished loading, images in preload queue get loaded. Loading happens sequentially one by one. Thus reducing stress to server.

Preloading code is based on mailing list post by Luke Lutman. Note that currently this code throws stack overflow with IE when there is more than 15 images to be preloaded. I am currently working on version which avoids this problem.

$(window).bind("load", function() {
    var preload = new Array();
    $(".hover").each(function() {
        s = $(this).attr("src").replace(/\.(.+)$/i, "_on.$1");
        preload.push(s)
    });
    var img = document.createElement('img');
    $(img).bind('load', function() {
        if(preload[0]) {
            this.src = preload.shift();
        }
    }).trigger('load');
});

After preloading I use following code to apply mouseovers. If there is image already which ends with string _on mouseover is removed.

$(document).ready(function() {
    $(".hover").each(function() {
        if ($(this).attr("src").match(/_on\.(.+)$/i)) {
            $(this).removeClass("hover");
        }
    });
    $(".hover").hover(function() {
        s = $(this).attr("src").replace(/\.(.+)$/i, "_on.$1");
        $(this).attr("src", s);
    }, function() {
        s = $(this).attr("src").replace(/_on\.(.+)$/i, ".$1");
        $(this).attr("src", s);
    });
});

For those who want to test. You can download snippet here.

UPDATE: You might also want to check how to lazy load images



When asking a question please include an URL to example page where the problem occurs. If you have longer code examples please use pastie.org.
CATEGORIES
Built using the awesome Flat UI Pro framework by Designmodo.

© 2013 Mika Tuupola.