UNPKG

@wezom/zz-load

Version:

Lazy loader based on IntersectionObserver API

108 lines (107 loc) 2.93 kB
var __assign = (this && this.__assign) || function () { __assign = Object.assign || function (t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; import attrs from './config/attrs'; import events from './config/events'; import check from './utils/check'; import getElements from './utils/get-elements'; import markAs from './utils/mark-as'; import load from './loads'; // ----------------------------------------------------------------------------- // Private // ----------------------------------------------------------------------------- var _defaultOptions = { rootMargin: '0px', threshold: 0, clearSourceAttrs: false, setSourcesOnlyOnLoad: true }; // ----------------------------------------------------------------------------- // Public // ----------------------------------------------------------------------------- export default function (elements, options) { if (options === void 0) { options = {}; } var _options = __assign(__assign({}, _defaultOptions), options); var observer = null; if (window.IntersectionObserver) { observer = new window.IntersectionObserver( function (entries, observer) { entries.forEach(function (entry) { var element = entry.target; var inViewType = element.hasAttribute(attrs.sourceInview); if (entry.intersectionRatio > 0 || entry.isIntersecting) { if (inViewType) { markAs(element, attrs.inView, events.inView, { visible: true }); load(element, _options); } else { observer.unobserve(element); load(element, _options); } } else { if (inViewType && check(element, attrs.inView)) { markAs( element, attrs.inView, events.inView, { visible: false }, true ); } } }); }, { rootMargin: _options.rootMargin, threshold: _options.threshold } ); } return { observe: function () { var list = getElements(elements); for (var i = 0; i < list.length; i++) { var element = list[i]; if (check(element, attrs.observed)) { continue; } markAs(element, attrs.observed, events.observed); if (observer === null) { load(element, _options); } else { observer.observe(element); } } }, triggerLoad: function (triggerElements, triggerOptions) { if (triggerOptions === void 0) { triggerOptions = {}; } var list = getElements(elements); var loadOptions = __assign(__assign({}, _options), triggerOptions); for (var i = 0; i < list.length; i++) { var element = list[i]; if (check(element, attrs.processed)) { continue; } markAs(element, attrs.observed, events.observed); load(element, loadOptions); } } }; }