前端开发有时候会有比较大的图片展示,而且还是在首屏,这个时候可以把图片预先加载出来。
js
const imgPreloader = url => {
return new Promise((resolve, reject) => {
let image = new Image();
image.onload = () => {
resolve();
};
image.onerror = () => {
reject();
};
image.src = url;
});
};
export const imgsPreloader = imgs => {
let promiseArr = [];
imgs.forEach(element => {
promiseArr.push(imgPreloader(element));
});
return Promise.all(promiseArr);
};
使用
js
(async () => {
const imgs = [require('@/assets/login_bg.png'), require('@/assets/left.png'), require('@/assets/logo@2x.png')];
await imgsPreloader(imgs);
renderHtml()
})()
加载图片的同时还可以在页面添加loading效果
html
<div id="app">
<div id="loading">
<div class="loader-inner round-waving">
<div></div>
<div></div>
<div></div>
</div>
</div>
</div>
<style type="text/css">
#loading {
top: 50%;
left: 50%;
position: absolute;
-webkit-transform: translateY(-50%) translateX(-50%);
transform: translateY(-50%) translateX(-50%);
z-index: 100;
}
@-webkit-keyframes round-waving {
50% {
opacity: 0.2;
-webkit-transform: scale(0.75);
transform: scale(0.75);
}
100% {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
}
@keyframes round-waving {
50% {
opacity: 0.2;
-webkit-transform: scale(0.75);
transform: scale(0.75);
}
100% {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
}
.round-waving > div {
background-color: #1d70f5;
width: 10px;
height: 10px;
border-radius: 100% !important;
margin: 2px;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
display: inline-block;
-webkit-animation: round-waving 0.7s 0s infinite linear;
animation: round-waving 0.7s 0s infinite linear;
}
.round-waving > div:nth-child(2n-1) {
-webkit-animation-delay: 0.35s !important;
animation-delay: 0.35s !important;
}
</style>