图片预加载插件开发小记
面向对象组件开发前端进阶不可或缺的一步,复用思想也是前端模块化的重要推动力
图片预加载在大批量图片加载的同时保证用户体验方面作用明显,浅显尝试,以此为记
插件封装(preLoad.js)
(function($) {
function PreLoad(imgs, options) {
this.imgs = imgs;
this.opts = $.extend({}, PreLoad.defaults, options);
this._loadnow();
this._addcli(imgs);
}
PreLoad.defaults = {
each: null,
all: null
}
PreLoad.prototype._loadnow = function() {
var imgs = this.imgs;
var opts = this.opts;
var count = 0;
var l = imgs.length;
$.each(imgs, function(i, src) {
var imgObj = new Image();
$(imgObj).on("load error", function() {
++count;
opts.each(count);
if(count >= l) {
opts.all();
}
});
imgObj.src = src;
})
}
PreLoad.prototype._addcli = function(imgs) {
var l = imgs.length;
var index = 0;
$("#prev").click(function() {
if(index < 1) return;
$(".box>img").attr('src', imgs[--index]);
})
$("#next").click(function() {
if(index >= l - 1) return;
$(".box>img").attr('src', imgs[++index]);
})
}
$.extend({
preload: function(imgs, options) {
new PreLoad(imgs, options);
}
});
})(jQuery)
插件使用
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
html,
body {
width: 100%;
height: 100%;
}
.box {
width: 1200px;
margin: 0 auto;
}
.btn {
width: 800px;
margin: 0 auto;
}
.btn>span {
width: 100px;
height: 30px;
line-height: 30px;
text-align: center;
background: #B3B3B3;
color: white;
cursor: pointer;
}
#prev {
float: left;
}
#next {
float: right;
}
.persent {
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
background-color: #B3B3B3;
}
.persent>p {
width: 30px;
height: 30px;
margin: 0 auto;
color: #fff;
font-size: 40px;
margin-top: 400px;
}
</style>
</head>
<body>
<div class="box">
<img src="http://desk.fd.zol-img.com.cn/t_s960x600c5/g5/M00/08/0B/ChMkJlmILU-IGd5HABRM9L5MfHUAAfd_AJ9MToAFE0M019.jpg" width="1200px" />
</div>
<div class="btn">
<span id="prev">上一页</span>
<span id="next">下一页</span>
</div>
<div class="persent">
<p><span id="num">0</span>%</p>
</div>
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="js/preLoad.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var imgs = [
'http://desk.fd.zol-img.com.cn/t_s960x600c5/g5/M00/08/0B/ChMkJlmILU-IGd5HABRM9L5MfHUAAfd_AJ9MToAFE0M019.jpg',
'http://desk.fd.zol-img.com.cn/t_s960x600c5/g5/M00/08/0B/ChMkJlmILU-IUKs0ABXhWXXbbckAAfd_AKRfkYAFeFx786.jpg',
'http://desk.fd.zol-img.com.cn/t_s960x600c5/g5/M00/0B/0B/ChMkJ1iUT3SIG2zFANNdJFXu3zUAAZrPwMMhC4A0108912.jpg',
'http://desk.fd.zol-img.com.cn/t_s960x600c5/g5/M00/00/06/ChMkJlgz_AGIcofsAAPk3-SsuUIAAX-ewKWFgIAA-T3540.jpg',
'http://desk.fd.zol-img.com.cn/t_s960x600c5/g5/M00/09/0D/ChMkJ1e2_LCITKqJAAoJpzIbrR4AAUkhwH3LZEACgm_374.jpg',
'http://desk.fd.zol-img.com.cn/t_s960x600c5/g5/M00/0B/07/ChMkJlbQIJGIcSlhABDJ3oQM3lIAALspQEYV2wAEMn2807.jpg',
];
$.preload(imgs, {
each: function(count) {
$("#num").text(Math.round((count) / imgs.length * 100));
// alert("nihao");
},
all: function() {
$(".persent").hide();
}
})
</script>
</body>
</html>
还没有评论,来说两句吧...