使用图片预加载可以在确保必要的图片加载完后,就显示页面,而不必等所有的图片加载完再显示页面,提升用户打开页面时的用户体验。
preloader.js
;(function(exports, undefined){
'use strict';
var document = exports.document;
var preloader = {
id: '',
imgUrls: [],
onInit: null,
onRemove: null
}
exports.preloader = preloader;
preloader.init = function(args){
for(var p in args){
this[p] = args[p];
}
this.preload.call(this, this.imgUrls);
if(this.onInit && typeof this.onInit === 'function'){
this.onInit();
}
}
preloader.remove = function(){
var pre = document.querySelector('#' + this.id);
document.body.removeChild(pre);
if(this.onRemove && typeof this.onRemove === 'function'){
this.onRemove();
}
}
preloader.preload = function(imgUrls){
var _this = this,
cnt = 0,
imgs = {};
imgUrls.forEach(function(item, index){
imgs[index] = new Image()
imgs[index].onload = function(){
if(++cnt === imgUrls.length){
_this.remove.call(_this);
}
}
imgs[index].src = item;
});
}
})(window);
index.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
<meta content="yes" name="apple-mobile-web-app-capable">
<meta content="black" name="apple-mobile-web-app-status-bar-style">
<meta content="telephone=no" name="format-detection">
<meta content="email=no" name="format-detection">
<title>preloader</title>
<link rel="stylesheet" href="./css/main.css">
<script src="./js/preloader.js"></script>
<script src="./js/main.js"></script>
</head>
<body>
<div class="preloader" id="preloader">
<div>加载中...</div>
</div>
<img src="./img/1.jpg">
<img src="./img/2.jpg">
<img src="./img/3.jpg">
<img src="./img/4.jpg">
<img src="./img/5.jpg">
<img src="./img/6.jpg">
<img src="./img/7.jpg">
<img src="./img/8.jpg">
</body>
</html>
main.css
html, body{
width: 100%;
margin: 0;
padding: 0;
overflow-x: hidden;
overflow-y: auto;
}
img{
width: 100%;
display: block;
}
.preloader{
width: 100%;
height: 100%;
position: fixed;
left: 0;
top: 0;
background-color: rgba(0, 0, 0, .9);
font-size: 24px;
color: #fff;
text-align: center;
}
.preloader>div{
width: 100%;
margin-top: 50%;
}
main.js
'use strict';
window.addEventListener('DOMContentLoaded', function(){
preloader.init({
id: 'preloader',
imgUrls: ['./img/1.jpg', './img/2.jpg', './img/3.jpg', './img/4.jpg', './img/5.jpg', './img/6.jpg', './img/7.jpg', './img/8.jpg'],
onInit: function(){
console.log('onInit');
},
onRemove: function(){
console.log('onRemove');
}
});
}, false);