js 预加载

预加载:提前加载
在加载较大图片,音频,视频时为了优化用户在打开我们项目时,避免遇到加载缓慢带来的不好的体验.
使用场景: 常用于 游戏,瀑布流

图片预加载:
图片预加载: 有很多的图片时,若一起加载,用户需要等待的事件较长,所有可以将项目中需要的资源提前加载好.

var img = new Image();
img.onload = function(){        
    document.body.appendChild(img);
}
img.src="http://reso3.yiihuu.com/img_1092742.jpg"

这样就完成了单张图片的预加载.
对于瀑布流的实现,要限定宽度的话.我们先获取盒子的宽度,计算出它的高度然后规定图片的高度就可以了.

var boxDiv = document.getElementById("box")
var img = new Image();
img.onload = function(){
    var w = boxDiv.offsetWidth;
    var h = w*img.height/img.width;
    boxDiv.style.height = h + "px";
    img.style.width = w+"px";
    boxDiv.appendChild(img);
}
img.src="http://reso3.yiihuu.com/img_1092742.jpg"

等待所有资源加载完成后显示:

1.将需要加载的图片的路径提前储存在数组中

var imgs = ["http://reso3.yiihuu.com/img_1092742.jpg",
"http://reso3.yiihuu.com/img_1092742.jpg",
"http://reso3.yiihuu.com/img_1092742.jpg"];

2.定义函数 实现预加载效果

.wrap{
    width: 400px;
    height: 600px;
    border: 1px solid;
    position: relative;
}
#loading{
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: lightcyan;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-content: center;
}

.bar{
    width: 300px;
    height: 30px;
    border: 2px solid green;
}
.progress{
    height: 30px;
    width: 0px;
    background: orange;
}
.game{
    width: 100%;
    height: 100%;
    background: orange;
}
<div class="wrap">
    <div id="loading">
        <div class="bar">
            <div class="progress">

            </div>  
        </div>
        <p>正在加载中... <span id="val"></span> </p>
    </div>
    <div class="game"></div>
</div>
/*
* arr 储存所有图片地址的数组
 * progress 回调函数 将加载的百分比传递给外界使用
 * complete 回调函数 所有图片加载完毕后提交给外界的处理函数
 */
function preloadImg(arr,progress,complete){
    var imgObjs = [];//储存所有加载好的图片资源
    var count = 0;//记录已加载好图片的数量
    for(var i = 0; i < arr.length; i++){
        var img = new Image();
        img.onload = function(){
            count++;
            var per = Math.floor(count/arr.length*100);
            typeof progress === "function" && progress(per);
            if(count == arr.length){
                //图片已全部加载完毕
                typeof complete === "function" && complete();
            }
        }
        imgObjs.push(img);
        img.src = arr[i];
    }
}

preloadImg(imgs,function(val){
    document.querySelector(".progress").style.width = val + "%";
        document.getElementById("val").innerHTML = val + "%";
    },function(){
        document.getElementById("loading").style.display = "none";

    });
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值