带型带秀专题之 Lazy Load (二)

参考文章:jQuery.lazyload使用及源码分析

关于 jQuery lazyload 插件的基本介绍和使用请看上一篇文章。(水水一章啦-。-)

Overview

让我们先从整体上看看代码的结构:

(function ($, window, document, undefined) {
  var $window = $(window);
  
  /* lazyload 方法主体 */
  $.fn.lazyload = function (options) {
  // ...
  }

  /* 在jQuery命名空间内定义了便捷的方法,判断图片是否在容器视口范围内 */
  $.belowthefold = function (element, settings) {...}
  $.rightoffold = function (element, settings) {...}
  $.abovethetop = function (element, settings) {...}
  $.leftofbegin = function (element, settings) {...}
  $.inviewport = function (element, settings) {...}

  /* 自定义选择器 */
  $.extend($.expr[":"], {...});
  
})(jQuery, window, document);

可以看一下注释,就不多做解释了。

选项

在上一节可以看到,使用lazyload最简单的方法像这样:

$('img.lazy').lazyload(); 

复杂一点的,我们可以传入一个选项对象自定义lazyload的表现。让我们从源码看一下所有可选的选项参数:

$.fn.lazyload = function (options) {
  var elements = this;
  var $container;
  
  // 默认配置
  var settings = {
    threshold       : 0,
    failure_limit   : 0,
    event           : "scroll.lazyload",
    effect          : "show",
    container       : window,
    data_attribute  : "original",
    data_srcset     : "srcset",
    skip_invisible  : false,
    appear          : null,
    load            : null,
    placeholder     : "data:image/gif;base64,R0lGODdhAQABAPAAAMPDwwAAACwAAAAAAQABAAACAkQBADs="
  }
}

分别解释一下:

threshold : 临界值

threshold: 0

这个值是针对container容器的,即距离container容器视口的临界值

event : 事件

event: "scroll.lazyload"

container容器默认绑定这个事件,在这个事件被触发时,会不断的判断img元素是否满足出发apper事件(即显示图片)的条件。默认的事件为scroll,你可以自定义这个事件。

effect :显示方法

effect: "show"

默认为show,也可以设置为fadeIn,源码中隐藏了一个配置属性:effectspeed,用于设置动画运行的时间。

data_attribute : 图片地址属性

data_attribute: "original"

img元素的一个data属性,用于存放图片的真实地址。

skip_invisible : 是否忽略隐藏的img元素

skip_invisible: false

设置为true时会忽略处理隐藏的img元素。

placeholder : 图片占位符

placeholder : "data:image/gif;base64,R0lGODdhAQABAPAAAMPDwwAAACwAAAAAAQABAAACAkQBADs="

lazyload会将该属性的值设置为img元素的初始src属性值。

appear

appear: null

在img触发load事件时执行的回调。

failure_limit

failure_limit: 0

为了便于理解,我们先来看一段与其有关的源码:

var counter = 0;

elements.each(function() {
    if ($.abovethetop(this, settings) || $.leftofbegin(this, settings)) {
        // ...
    } else if (!$.belowthefold(this, settings) && !$.rightoffold(this, settings)) {
        // ...
    } else {
        if (++counter > settings.failure_limit) {
            return false;
        }
    }
});

如果找到的是第failure_limit个img元素,且不在container视口上方,左方及视口内(可以允许在视口下方,右方),则中断循环。

两个示例:

demo1 下拉滚动: http://jsfiddle.net/ddEPL/
demo2 Tab切换: http://jsfiddle.net/ddEPL/1/>…

源码分析

/*
 * Lazy Load - jQuery plugin for lazy loading images
 *
 * Copyright (c) 2007-2013 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://www.appelsiini.net/projects/lazyload
 *
 * Version:  1.9.3
 *
 */

(function($, window, document, undefined) {
    var $window = $(window);

    $.fn.lazyload = function(options) {
        var elements = this;
        var $container;
        var settings = {
            threshold       : 0,
            failure_limit   : 0,
            event           : "scroll",
            effect          : "show",
            container       : window,
            data_attribute  : "original",
            skip_invisible  : true,
            appear          : null,
            load            : null,
            placeholder     : "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC"
        };

        function update() {
            var counter = 0;

            elements.each(function() {
                var $this = $(this);
                // 如果图片隐藏,且忽略隐藏,则中断循环
                if (settings.skip_invisible && !$this.is(":visible")) {
                    return;
                }
                if ($.abovethetop(this, settings) || $.leftofbegin(this, settings)) {
                        /* Nothing. */
                } 
                // img满足在container视口中,则显示
                else if (!$.belowthefold(this, settings) && !$.rightoffold(this, settings)) {
                        $this.trigger("appear");
                        /* if we found an image we'll load, reset the counter */
                        counter = 0;
                }
                // 如果找到的是第(failure_limit + 1)个img元素,且不在container视口上方,左方及视口内(可以允许在视口下方,右方),
                // 则中断循环
                else {
                    if (++counter > settings.failure_limit) {
                        return false;
                    }
                }
            });

        }

        if(options) {
            /* Maintain BC for a couple of versions. */
            if (undefined !== options.failurelimit) {
                options.failure_limit = options.failurelimit;
                delete options.failurelimit;
            }
            if (undefined !== options.effectspeed) {
                options.effect_speed = options.effectspeed;
                delete options.effectspeed;
            }

            $.extend(settings, options);
        }

        /* Cache container as jQuery as object. */
        $container = (settings.container === undefined ||
                      settings.container === window) ? $window : $(settings.container);

        /* Fire one scroll event per scroll. Not one scroll event per image. */
        // 为container绑定scroll事件
        if (0 === settings.event.indexOf("scroll")) {
            $container.bind(settings.event, function() {
                return update();
            });
        }

        this.each(function() {
            var self = this;
            var $self = $(self);

            self.loaded = false;

            /* If no src attribute given use data:uri. */
            // 设置占位符
            if ($self.attr("src") === undefined || $self.attr("src") === false) {
                if ($self.is("img")) {
                    $self.attr("src", settings.placeholder);
                }
            }

            /* When appear is triggered load original image. */
            // one绑定appear,触发后则移除该事件
            $self.one("appear", function() {
                if (!this.loaded) {
                    // 存在回调则触发
                    if (settings.appear) {
                        var elements_left = elements.length;
                        settings.appear.call(self, elements_left, settings);
                    }
                    $("<img />")
                        .bind("load", function() {

                            var original = $self.attr("data-" + settings.data_attribute);
                            $self.hide();
                            if ($self.is("img")) {
                                $self.attr("src", original);
                            } else {
                                $self.css("background-image", "url('" + original + "')");
                            }
                            $self[settings.effect](settings.effect_speed);

                            self.loaded = true;

                            /* Remove image from array so it is not looped next time. */
                            // 更新elements,过滤掉已经加载的img元素,避免下次在update中轮循
                            var temp = $.grep(elements, function(element) {
                                return !element.loaded;
                            });
                            elements = $(temp);
                            
                            // 存在回调则触发
                            if (settings.load) {
                                var elements_left = elements.length;
                                settings.load.call(self, elements_left, settings);
                            }
                        })
                        .attr("src", $self.attr("data-" + settings.data_attribute));
                }
            });

            /* When wanted event is triggered load original image */
            /* by triggering appear.                              */
            // 绑定不是scroll的事件,用于触发appear事件
            if (0 !== settings.event.indexOf("scroll")) {
                $self.bind(settings.event, function() {
                    if (!self.loaded) {
                        $self.trigger("appear");
                    }
                });
            }
        });

        /* Check if something appears when window is resized. */
        $window.bind("resize", function() {
            update();
        });

        /* With IOS5 force loading images when navigating with back button. */
        /* Non optimal workaround. */
        if ((/(?:iphone|ipod|ipad).*os 5/gi).test(navigator.appVersion)) {
            $window.bind("pageshow", function(event) {
                if (event.originalEvent && event.originalEvent.persisted) {
                    elements.each(function() {
                        $(this).trigger("appear");
                    });
                }
            });
        }

        /* Force initial check if images should appear. */
        $(document).ready(function() {
            update();
        });

        return this;
    };

    /* Convenience methods in jQuery namespace.           */
    /* Use as  $.belowthefold(element, {threshold : 100, container : window}) */

    $.belowthefold = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = (window.innerHeight ? window.innerHeight : $window.height()) + $window.scrollTop();
        } else {
            fold = $(settings.container).offset().top + $(settings.container).height();
        }

        return fold <= $(element).offset().top - settings.threshold;
    };

    $.rightoffold = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.width() + $window.scrollLeft();
        } else {
            fold = $(settings.container).offset().left + $(settings.container).width();
        }

        return fold <= $(element).offset().left - settings.threshold;
    };

    $.abovethetop = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.scrollTop();
        } else {
            fold = $(settings.container).offset().top;
        }

        return fold >= $(element).offset().top + settings.threshold  + $(element).height();
    };

    $.leftofbegin = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.scrollLeft();
        } else {
            fold = $(settings.container).offset().left;
        }

        return fold >= $(element).offset().left + settings.threshold + $(element).width();
    };

    $.inviewport = function(element, settings) {
         return !$.rightoffold(element, settings) && !$.leftofbegin(element, settings) &&
                !$.belowthefold(element, settings) && !$.abovethetop(element, settings);
     };

    /* Custom selectors for your convenience.   */
    /* Use as $("img:below-the-fold").something() or */
    /* $("img").filter(":below-the-fold").something() which is faster */

    $.extend($.expr[":"], {
        "below-the-fold" : function(a) { return $.belowthefold(a, {threshold : 0}); },
        "above-the-top"  : function(a) { return !$.belowthefold(a, {threshold : 0}); },
        "right-of-screen": function(a) { return $.rightoffold(a, {threshold : 0}); },
        "left-of-screen" : function(a) { return !$.rightoffold(a, {threshold : 0}); },
        "in-viewport"    : function(a) { return $.inviewport(a, {threshold : 0}); },
        /* Maintain BC for couple of versions. */
        "above-the-fold" : function(a) { return !$.belowthefold(a, {threshold : 0}); },
        "right-of-fold"  : function(a) { return $.rightoffold(a, {threshold : 0}); },
        "left-of-fold"   : function(a) { return !$.rightoffold(a, {threshold : 0}); }
    });

})(jQuery, window, document);
    原文作者:t1ree
    原文地址: https://segmentfault.com/a/1190000011826918
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞