lazyLoad.js 1.4 KB
require('intersection-observer');
var imgSrcHandle =require('./img-src-handle');

function lazyLoad(obj) {
    var _this = this;
    this.conf = {
        srcTarget: obj && obj.srcTarget || 'data-src',
        selector: obj && obj.selector || '.yo-lazy'
    };
    this.io = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
            if (entry.intersectionRatio > 0) {
                _this.io.unobserve(entry.target);
                var src = entry.target.getAttribute(_this.conf.srcTarget);
                if ("img" === entry.target.tagName.toLowerCase()) {
                    if (src) {
                        entry.target.src = src;
                    }
                } else {
                    entry.target.style.backgroundImage = "url(" + imgSrcHandle(src) + ")";
                }
                entry.target.setAttribute('data-load','false')
            }
        })
    }, {
        root: null,
        rootMargin: "0px",
        threshold: [0]
    })
    var imgs = document.querySelectorAll(this.conf.selector);
    this.loading = function () {
        imgs.forEach(function (value) {
            _this.io.observe(value);
        })
    };

}

module.exports = function (obj) {
    var lazy = new lazyLoad(obj);
    if (typeof window.supportWebp !== 'undefined') {
        lazy.loading();
    } else {
        document.addEventListener('supportWebp', lazy.loading);
    }
};