如何用jquery做行预加载器

How to do line preloader with jquery

本文关键字:加载 何用 jquery      更新时间:2023-09-26


我尝试了这个代码的行预加载器,但它没有工作,我不知道问题在哪里。

var $preload = $("<div class='preloader'><div class='percent'></div><div class='line-parent'><div class='line'></div></div></div>");
$("body").prepend($preload);
var $imgs = $("img");
var imgsLoaded = 0;
var ratio = 0;
$imgs.each(function(){
    $this = $(this);
    $this.load(function(){ 
        imgsLoaded++;
        ratio = imgsLoaded / $imgs.length;
        $(".percent").html(ratio / 0.01 + "%");
        $(".line").animate({
            width : ratio / 0.01 + "%"
        });
    }, function(){
        if(ratio === 1){
            $(".preloader").fadeOut();
        }
    });
});

我相信您想要在所有图像加载并执行一些操作时显示100%。如果在图像已经加载后附加第一次加载事件,将无法工作。

我建议检查每个img complete和naturalWidth属性每100毫秒(setInterval)。

Loader = (function() {
var list, img_length, loaded, interval;
function _check_one(i) { o = list[i]; if (o.complete == true && o.naturalWidth > 0) { loaded++; delete list[i]; } };
function _procent(l, a) { console.log((100*loaded/img_length) + '%'); }
function _check_list() { for(var i in list) {_check_one(i)};_procent();_kill(); };
function _kill() { if(img_length <= loaded) clearInterval(interval); }
function _start() { loaded = 0; list = $('img'); img_length = list.length; 
if(img_length != loaded) interval = setInterval(_check_list, 100); }
return { start: _start }
})();

现在在正文的末尾或者$(document).ready(…)中你需要调用Loader.start();

或将所有图像源(src)放在data-src attribite中,附加加载事件并复制data-scr到src attribite。在正文中,所有相关图像看起来像这样:

<img data-src="some url">...

脚本标签:

$('img').on('load', function() {
// Your action.
}).each(function() { var img = $(this); img.attr('src', img.attr('data-src')); });