当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 关于js预加载的代码实现

关于js预加载的代码实现

2018年08月20日  | 移动技术网IT编程  | 我要评论

预加载:提前加载

在加载较大图片,音频,视频时为了优化用户在打开我们项目时,避免遇到加载缓慢带来的不好的体验.

使用场景: 常用于 游戏,瀑布流

图片预加载:

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

var img = new image();
img.onload = function(){        
    document.body.appendchild(img);
}
img.src="https://www.2cto.com/uploadfile/2018/0712/20180712123217408.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="https://www.2cto.com/uploadfile/2018/0712/20180712123217408.jpg"

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

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

var imgs = ["https://www.2cto.com/uploadfile/2018/0712/20180712123217408.jpg",
"https://www.2cto.com/uploadfile/2018/0712/20180712123217408.jpg",
"https://www.2cto.com/uploadfile/2018/0712/20180712123217408.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;
}
/*
* 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";

    });

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网