预加载:提前加载
在加载较大图片,音频,视频时为了优化用户在打开我们项目时,避免遇到加载缓慢带来的不好的体验.
使用场景: 常用于 游戏,瀑布流
图片预加载:
图片预加载: 有很多的图片时,若一起加载,用户需要等待的事件较长,所有可以将项目中需要的资源提前加载好.
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";
});

本文介绍了一种提升用户体验的技术——图片预加载。通过提前加载图片资源,避免了用户在浏览项目时因图片加载缓慢而导致的不佳体验。文章详细阐述了如何实现单张图片预加载,并进一步解释了在瀑布流布局中如何限定图片宽度并保持其比例。
367

被折叠的 条评论
为什么被折叠?



