lazyload fadeIn基于纯Javascript的效果

时间:2017-09-01 10:23:35

标签: javascript css optimization scroll lazyload

我正在尝试执行延迟加载效果并从这段伟大的代码中添加类似fadeIn效果的内容:

(function (root, factory) {
    if (typeof define === "function" && define.amd) {
        define([], factory(root));
    } else if (typeof exports === "object") {
        module.exports = factory(root);
    } else {
        root.LazyLoad = factory(root);
    }
}) (typeof global !== "undefined" ? global : this.window || this.global, function (root) {

"use strict";

const defaults = {
    src: "data-src",
    srcset: "data-srcset",
    selector: ".lazyload"
};

/**
* Merge two or more objects. Returns a new object.
* @private
* @param {Boolean}  deep     If true, do a deep (or recursive) merge [optional]
* @param {Object}   objects  The objects to merge together
* @returns {Object}          Merged values of defaults and options
*/
const extend = function ()  {

    let extended = {};
    let deep = false;
    let i = 0;
    let length = arguments.length;

    /* Check if a deep merge */
    if (Object.prototype.toString.call(arguments[0]) === "[object Boolean]") {
        deep = arguments[0];
        i++;
    }

    /* Merge the object into the extended object */
    let merge = function (obj) {
        for (let prop in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, prop)) {
                /* If deep merge and property is an object, merge properties */
                if (deep && Object.prototype.toString.call(obj[prop]) === "[object Object]") {
                    extended[prop] = extend(true, extended[prop], obj[prop]);
                } else {
                    extended[prop] = obj[prop];
                }
            }
        }
    };

    /* Loop through each object and conduct a merge */
    for (; i < length; i++) {
        let obj = arguments[i];
        merge(obj);
    }

    return extended;
};

function LazyLoad(images, options) {
    this.settings = extend(defaults, options || {});
    this.images = images || document.querySelectorAll(this.settings.selector);
    this.observer = null;
    this.init();
}

LazyLoad.prototype = {
    init: function() {

        /* Without observers load everything and bail out early. */
        if (!root.IntersectionObserver) {
            this.loadImages();
            return;
        }

        let self = this;
        let observerConfig = {
            root: null,
            rootMargin: "0px",
            threshold: [0]
        };

        this.observer = new IntersectionObserver(function(entries) {
            entries.forEach(function (entry) {
                if (entry.intersectionRatio > 0) {
                    self.observer.unobserve(entry.target);
                    let src = entry.target.getAttribute(self.settings.src);
                    let srcset = entry.target.getAttribute(self.settings.srcset);
                    if ("img" === entry.target.tagName.toLowerCase()) {
                        if (src) {
                            entry.target.src = src;
                        }
                        if (srcset) {
                            entry.target.srcset = srcset;
                        }
                    } else {
                        entry.target.style.backgroundImage = "url(" + src + ")";
                    }
                }
            });
        }, observerConfig);

        this.images.forEach(function (image) {
            self.observer.observe(image);
        });
    },

    loadAndDestroy: function () {
        if (!this.settings) { return; }
        this.loadImages();
        this.destroy();
    },

    loadImages: function () {
        if (!this.settings) { return; }

        let self = this;
        this.images.forEach(function (image) {
            let src = image.getAttribute(self.settings.src);
            let srcset = image.getAttribute(self.settings.srcset);
            if ("img" === image.tagName.toLowerCase()) {
                if (src) {
                    image.src = src;
                }
                if (srcset) {
                    image.srcset = srcset;
                }
            } else {
                image.style.backgroundImage = "url(" + src + ")";
            }
        });
    },

    destroy: function () {
        if (!this.settings) { return; }
        this.observer.disconnect();
        this.settings = null;
    }
};

root.lazyload = function(images, options) {
    return new LazyLoad(images, options);
};

if (window.jQuery) {
    const $ = window.jQuery;
    $.fn.lazyload = function (options) {
        options = options || {};
        options.attribute = options.attribute || "data-src";
        new LazyLoad($.makeArray(this), options);
        return this;
    };
}

return LazyLoad;
 });

我不能,你对如何开始有任何建议吗?它来自这个autor的代码:

https://github.com/tuupola/jquery_lazyload/blob/2.x/lazyload.js他的git上也有laxload 1.x版本,但首先它基于jQuery,我想尝试学习一些Javascript,其次是1.x在滚动事件上更改DOM我想避免因为它会伤害性能

1 个答案:

答案 0 :(得分:0)

首先,我设置了休息时间&gt;在chrome dev工具上修改属性并刷新页面,它显示了设置src值:

if ("img" === entry.target.tagName.toLowerCase()) {
    if (src) {
        entry.target.src = src;            

键是entry.target.src = src;设置src的地方,

其次我将.lazyload类的不透明度设置为0,之后我尝试删除类.lazyload并使用css添加类.lazierload:

.lazierload{
 opacity:1;
 transition: opacity 1s ease;
}

在javascript中看起来像是:

if ("img" === entry.target.tagName.toLowerCase()) {
  if (src) {
     entry.target.src = src; 
     entry.target.classList.remove("lazyload")
     entry.target.classList.add("lazierload");
  }

但它仍然不起作用,src属性仍然是设置类更改,但过渡效果不会出现,图像只是加载像lazyload而没有这个所有额外的代码