UNPKG

@axe/lazy-load-img

Version:

A library of lazy load image when it is necessary.

101 lines (86 loc) 3.12 kB
import "core-js/modules/web.dom.iterable"; import "core-js/modules/es6.array.for-each"; import { throttle } from './utils'; var LazyLoadImg = function () { function LazyLoadImg(_ref) { var el = _ref.el, _ref$scrollEl = _ref.scrollEl, scrollEl = _ref$scrollEl === void 0 ? document.documentElement : _ref$scrollEl, _ref$lazyOffsetTop = _ref.lazyOffsetTop, lazyOffsetTop = _ref$lazyOffsetTop === void 0 ? 0 : _ref$lazyOffsetTop, placeholderImg = _ref.placeholderImg, onImgLoad = _ref.onImgLoad, _ref$cutTime = _ref.cutTime, cutTime = _ref$cutTime === void 0 ? 100 : _ref$cutTime; this.scrollEl = typeof scrollEl !== 'string' ? scrollEl : document.querySelector(scrollEl); this.el = typeof el !== 'string' ? el : scrollEl && scrollEl.querySelector(el); this.lazyOffsetTop = lazyOffsetTop; this.placeholderImg = placeholderImg; this.onImgLoad = onImgLoad; this.cutTime = cutTime; this.imgList = []; this.loadedImg = {}; this.init(); this._initEvent(); } var _proto = LazyLoadImg.prototype; _proto._initEvent = function _initEvent() { var _this = this; var realScrollEl = this.scrollEl === document.documentElement ? window : this.scrollEl; var fn = throttle(function () { _this.update(); }, this.cutTime); window.addEventListener('resize', fn, false); realScrollEl.addEventListener('scroll', fn, false); }; _proto.init = function init() { var _this2 = this; if (!this.el) return; this.imgList = []; var imgList = this.el.getElementsByTagName('img'); if (!imgList.length) return; for (var i = 0, l = imgList.length; i < l; i++) { if (imgList[i].getAttribute('data-src')) { this.imgList.push(imgList[i]); } } if (!this.placeholderImg || this.loadedImg[this.placeholderImg]) { this.update(); } else { var img = new Image(); img.src = this.placeholderImg; img.addEventListener('load', function () { _this2.loadedImg[img.src] = true; _this2.update(); }, false); } }; _proto.update = function update() { var _this3 = this; if (!this.imgList.length) return; var remainImgList = []; var clientHeight = this.scrollEl.clientHeight; this.imgList.forEach(function (img) { var rect = img.getBoundingClientRect(); var lazySrc = img.getAttribute('data-src'); if (rect.top <= clientHeight + _this3.lazyOffsetTop && rect.bottom + _this3.lazyOffsetTop >= 0) { if (!_this3.loadedImg[lazySrc]) { var loadImg = new Image(); loadImg.src = lazySrc; loadImg.addEventListener('load', function () { img.src = lazySrc; _this3.loadedImg[lazySrc] = true; _this3.onImgLoad && _this3.onImgLoad(img, loadImg.width, loadImg.height); }, false); } else { img.src = lazySrc; } } else { remainImgList.push(img); } }); this.imgList = remainImgList; }; return LazyLoadImg; }(); export { LazyLoadImg as default };