开发者

How to display a loading bar for images with jQuery?

开发者 https://www.devze.com 2023-02-28 13:09 出处:网络
I have images on my p开发者_开发问答age. I want to show a loading bar on my page, showing the progress of the downloaded images.

I have images on my p开发者_开发问答age.

I want to show a loading bar on my page, showing the progress of the downloaded images.

How can I do this?


I have written a jQuery plugin to register callbacks for images loading.

You would use it like so...

var loading = $('<div id="loading" />').appendTo('body');

$('body').waitForImages(function() {
   loading.remove();
 }, function(loaded, all) {
   loading.html(((loaded / all) * 100) + '% loaded');
});

jsFiddle.


var preload = function (images, callback) {
    var count = 0;
    for (var i = 0, len = images.length; i < len; i++) {
        var img = new Image();
        img.src = images[i];
        img.onload = function () {
            var perc = ++count * (100 / len) | 0;
            if (callback) callback.call(this, perc, perc === 100);
        };
    }
};

The usage is pretty simple:

preload(['http://lorempixel.com/800/600'], function(perc, done) {
    console.log( perc);
    if(done) console.log( 'Done!' );
    // `this` refers to each loaded image.
});
0

精彩评论

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