1 /**
2 * picLazyLoad 圖片延時加載,包含背景圖片
3 * $(img).picLazyLoad({...})
4 * data-original 預加載圖片地址
5 * alon
6 */
7 ;(function($){
8 $.fn.imgLazyLoad = function(settings){
9 var $this = $(this),
10 _winScrollTop = 0,
11 _winHeight = $(window).height();
12 settings = $.extend({
13 threshold: 0, // 提早高度加載
14 placeholder: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC',
15 callback:function(){}
16 }, settings||{});
17 // 執行懶加載圖片
18 lazyLoadPic();
19 // 滾動觸發換圖
20 $(window).on('scroll',function(){
21 _winScrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
22 lazyLoadPic();
23 });
24 // 懶加載圖片
25 function lazyLoadPic(){
26 $this.each(function(){
27 var $self = $(this);
28 if($self.is('img')){
29 if($self.attr('data-original')){
30 var _offsetTop = $self.offset().top;
31 if((_offsetTop - settings.threshold) <= (_winHeight + _winScrollTop)){
32 $self.attr('src',$self.attr('data-original'));
33 $self.removeAttr('data-original');
34 $self.removeClass('loadH');
35 settings.callback($self);
36 }
37 }
38 }else{
39 if($self.attr('data-original')){// 默認佔位圖片
40 if($self.css('background-image') == 'none'){
41 $self.css('background-image','url('+settings.placeholder+')');
42 }
43 var _offsetTop = $self.offset().top;
44 if((_offsetTop - settings.threshold) <= (_winHeight + _winScrollTop)){
45 $self.css('background-image','url('+$self.attr('data-original')+')');
46 $self.removeAttr('data-original');
47 settings.callback($self);
48 }
49 }
50 }
51 });
52 }
53 }
54 })(Zepto);
調用
1 $('img').imgLazyLoad({callback:function(data){
2
3 })