开发者

jQuery: any suggestions how to preload all images in dom sequentially?

any ideas about it? any plugin? I wan开发者_StackOverflow社区t find all img tag and show them sequentially? thank you


Create a small jQuery utility method:

jQuery.preloadImages = function() {
    var set = jQuery('img');
    var current = 0;
    var iterate = function() {
        var current_src = set[current].src;
        var temp = jQuery('<img/>');
        jQuery(temp).bind('load', function() {
            console.log($(this).attr('src') + ' loaded');
            jQuery(this).remove(); //remove temp image from DOM.
        });

        temp[0].src = current_src;
        jQuery('body').append(temp);
        if(++current < set.length) iterate(); //recursive call
    };
    iterate();
};

Invoke this like such:

$.preloadImages();

jsFiddle example


Go through this


I used this function on a website to preload a list of images in a specific order sequentially:

It also maintains a progress indicator.

MicrositeMedia.ImagePreLoader = function (_settings) {
var self = this;

var defaults = {
    list: [],
    rootpath: '',
    onFinished: function () { },
    onItemFinished: null,
    containerId: '#preload-container'
}

this.settings = $.extend(defaults, _settings);
this.progressElm = 'preloadProgressIndicator';
//this.settings.list.pop();
var listSize = _settings.list.length;

MicrositeUtils.Logger.log("listSize: " + listSize);

this.current = 0;

this.init = function () {
    //MicrositeUtils.Logger.log("ImagePreLoader - init()");
    // 
    $(this.settings.containerId).show();
    this.loadNext();
}

// list of already loaded items
var loadList = [];
var curImg = new Image();

this.loadNext = function () {
    if (listSize && listSize != 0) {
        // our current Image object
        var key = this.settings.list.shift();


        curImg.src = this.settings.rootpath + key;

        curImg.onerror = function () {
            //this.loadNext();
            MicrositeUtils.Logger.log("Error while loading image" + curImg.src.toString());
        }

        //MicrositeUtils.Logger.log('curImg.src: ' + curImg.src);
        // when it loads, it triggers the next load event.
        curImg.onload = function () {
            // item loading finished                
            //MicrositeUtils.Logger.log("current: " + key + ", src :" + curImg.src + "current: " + self.current);
            loadList.push(curImg.src);

            // fire single item loaded event.
            if (self.settings.onItemFinished) {
                self.settings.onItemFinished(self.current, curImg.src);
            }

            // next
            self.current += 1;

            // update loader progress indicator.
            self.updateProgressIndicator(curImg.src, self.current, listSize);


            MicrositeUtils.Logger.log("loading image " + self.current + "/" + listSize);
            if (self.current == listSize) {
                // last element has loaded, fire the complete event
                self.complete();

            }
            else {
                // call the next one recursively
                self.loadNext();

            }

        };

    }
    else {
        MicrositeUtils.Logger.log("ImageLoader.loadNext(): nothing to load!");
    }
}


this.complete = function () {

    // clean up
    $(this.settings.containerId).fadeOut('slow', function () {
        // last element has loaded, fire the onfinished event
        if (self.settings.onFinished) self.settings.onFinished();
    });

}

this.updateProgressIndicator = function (text, idx, max) {
    var elm = this.progressElm;
    var percent = (Math.round((idx / max) * 100)) + "%";

    if (!document.getElementById(elm)) {
        // insert element
        $('<div id="' + elm + '"></div>')
            .appendTo(this.settings.containerId);
    }

    //MicrositeUtils.Logger.log(percent);
    $('#' + elm).html(percent);
}

}

I called it like this:

this.imagePreloader = new MicrositeMedia.ImagePreLoader({
        list: preloadList,
        rootpath: self.appPath + '/assets/images',
        onFinished: function () {
            //MicrositeUtils.Logger.log("Preload (onfinished) - all done!");
            self.LoadInitialSection();
        },
        onItemFinished: function (item, src) {
            //MicrositeUtils.Logger.log("Preload (onitemfinished) - [item, src]: [" + item + ", " + src + "]");
        }
    });

    this.imagePreloader.init();

list is the array of image names.

rootpath is, as the name suggests, a the path prefix for all the images you need to preload. It's your application's images path, in general.

containerId is your preloader Container, if you want to use a background and a progress indicator. If you need only preloading in the background, set this to en empty string.

onFinished contains normally a function which fires, when all preloading is finished. Typically, you can present your images at this point.

onItemFinished is a function you need fired after each image loaded.

You can omit the MicrositeUtils.Logger.log function or just implement it with your own routine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜