August 19, 2011

jQuery loadNicely - load your images...nicely

It’s fairly common practice these days to give web site visitors some indication of progress, particularly when loading content or performing an action via ajax.

So why can’t we do the same when loading images?

loadNicely is a litte jQuery plugin that provides a callback function when an image is ready to be displayed (the browser has fully loaded the source of the image).

By default it will fade each image in, but you can override the ‘onLoad’ and ‘preload’ functions.

(function ($) {

    $.fn.loadNicely = function (options) {

        var defaults = {
            preLoad: function (img) { },
            onLoad: function (img) { $(img).fadeIn(200); }
        };

        var options = $.extend(defaults, options);

        return this.each(function () {
   
            if (!this.complete) {
                options.preLoad(this);
                $(this).load(function () { options.onLoad(this); }).attr("src", this.src);
            }
            else {
                options.onLoad(this);
            }
        });
    };
})(jQuery);

In the example below we make use of the excellent spin.js plugin to show a loading animation whilst the image loads.

var spinnerOptions = {
    lines: 10, // The number of lines to draw
    length: 3, // The length of each line
    width: 2, // The line thickness
    radius: 3, // The radius of the inner circle
    color: '#000', // #rbg or #rrggbb
    speed: 1, // Rounds per second
    trail: 60, // Afterglow percentage
    shadow: false // Whether to render a shadow
};

$("img").loadNicely({
    preload: function (img) {
        $(img).parent().spin(spinnerOptions);
    },
    onLoad: function (img) {
        $(img).fadeIn(200, function () {
            var spinner = $(this).parent().data("spinner");
            if (spinner)
                spinner.stop();
        });
    }
});

In the “preload” function we add the spinner to the image’s parent element. In the “onLoad” function we stop it.

loadNicely plugin

You’ll need to give the parent element a fixed width, height (ideally the same size as the image). Spin.js will then automatically centrally align the spinner.

Tested in latest version of Chrome, Firefox and IE. I’m far from a Javascript guru, so if it can be improved, let me know.

22.08.11 - Updated plugin to handle images that fail to load and added fix for IE9 load issue.
23.10.11 - Updated to latest version.

© 2022 Ben Foster