首页 > 代码库 > 懒加载
懒加载
<body>
<div class="wrapper">
<img src="http://www.mamicode.com/img/bg_2_01.jpg" alt="images1" data-src="http://www.mamicode.com/img/bg_2_01.jpg">
<img src="http://www.mamicode.com/img/bg_2_02.jpg" alt="images2" data-src="http://www.mamicode.com/img/bg_2_02.jpg">
<img src="http://www.mamicode.com/img/gif.png" alt="images3" data-src="http://www.mamicode.com/img/bg_2_03.jpg">
<img src="http://www.mamicode.com/img/gif.png" alt="images4" data-src="http://www.mamicode.com/img/bg_2_04.jpg">
<img src="http://www.mamicode.com/img/gif.png" alt="images5" data-src="http://www.mamicode.com/img/bg_2_05.jpg">
<img src="http://www.mamicode.com/img/gif.png" alt="images6" data-src="http://www.mamicode.com/img/bg_2_06.jpg">
<img src="http://www.mamicode.com/img/gif.png" alt="images7" data-src="http://www.mamicode.com/img/bg_2_07.jpg">
<img src="http://www.mamicode.com/img/gif.png" alt="images8" data-src="http://www.mamicode.com/img/bg_2_08.jpg">
<a href="http://www.mamicode.com/tel:400-799-5511">
<img class="tell_phone" src="http://www.mamicode.com/img/gif.png" alt="images_btn1" data-src="http://www.mamicode.com/img/btn2_03.png" ></a>
<a href="http://wx.guangguang.net.cn/fdmall/index.php">
<img class="buy_btn" src="http://www.mamicode.com/img/gif.png" alt="images_btn2" data-src="http://www.mamicode.com/img/btn_06.png" >
</a>
</div>
<script type="text/javascript" src="http://www.mamicode.com/js/libs/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
(function(){
‘use strict‘;
var $window = $(window);
var $document = $(document);
var $img = $(‘img‘);
var imgLength = $(‘img‘).length;
var self = $(this);
var imgSrc = http://www.mamicode.com/‘img/gif.png‘;
var lazyload = {
init:function(){
this.bind()
},
bind:function() {
var change = 1;
var imgObj= new Image();
$window.scroll(function(){
if (change==2) return ;
var $winScrollTop = parseInt($window.scrollTop(),10) ;
var $winHeight = parseInt($window.height(),10);
$img.each(function(a,n){
if($img.eq(a).offset().top < ($winScrollTop + $winHeight ) ){
if($img.eq(a).attr(‘src‘) == imgSrc ){
var data_src = http://www.mamicode.com/$img.eq(a).attr(‘data-src‘);
$img.eq(a).attr(‘src‘,data_src);
}
}
})
})
function imgOnload(){
for (var i=0;i<imgLength;){
if($img[i].complete && $img.eq(i).attr(‘src‘)!=imgSrc){
i++;
}else{
$img[i].src=http://www.mamicode.com/$img.eq(i).attr(‘data-src‘);
i++;
}
}
change=2;
}
setTimeout(imgOnload,500)
}
}
lazyload.init();
})()
</script>
</body>
懒加载