首页 > 代码库 > 资源百分比预加载

资源百分比预加载

JS代码 :

var loadNum = 0,
    resource = [
        ‘aaa.gif‘,
        ‘1.gif‘,
        ‘2.gif‘,
        ‘https://gss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/d439b6003af33a872e9fa4dac35c10385243b504.jpg‘,
        ‘images/layer1.jpg‘,
        ‘images/layer2.jpg‘,
        ‘images/layer3.jpg‘
    ],
    resLen = resource.length;

for (var i = 0; i < resLen; i++) {  
 var Images = new Image();
        Images.src = resource[i];
    if (Images.complete) { //如果缓存里有这张图片,就是触发complete
        loadNum++;
        var percent = Math.floor(loadNum / resLen * 100);
        setNum(percent);
        continue;
    }
    Images.onload = function() { //图片加载
        loadNum++;
        var percent = Math.floor(loadNum / resLen * 100);
        setNum(percent);
    };
}
function setNum(percent) {
    $("#bfb").text(percent); //设置百分数到DOM上
    if (percent == 100) {
        setTimeout(function() {
            //   do something;
        }, 300);
    }
}

 

html:

<div id="bfb"></div>

 

资源百分比预加载