UNPKG

@wezom/zz-load

Version:

Lazy loader based on IntersectionObserver API

98 lines (97 loc) 2.84 kB
import markAs from '../utils/mark-as'; import attrs from '../config/attrs'; import events from '../config/events'; import check from '../utils/check'; import sanitizeAttrs from '../utils/sanitize-attrs'; import loadSourceImg from './source-img'; import loadSourceBgImg from './source-bg-img'; import loadSourceIframe from './source-iframe'; import loadSourcePicture from './source-picture'; export default function (element, options, asPromise) { var load = function (resolve, reject) { markAs(element, attrs.processed, events.processed); if (options.onProcess !== undefined) { options.onProcess(element); } function loadActions(loadEvent, resource) { if (options.clearSourceAttrs && !check(element, 'inView')) { sanitizeAttrs(element); } markAs(element, attrs.loaded, events.loaded, { loadEvent: loadEvent, resource: resource }); if (options.onLoad !== undefined) { options.onLoad(element, resource); } resolve(element, resource); } function errorActions(errorEvent, resource) { markAs(element, attrs.failed, events.failed, { errorEvent: errorEvent, resource: resource }); if (options.onFail !== undefined) { options.onFail(element, resource); } reject(element); } // img var sourceImg = element.getAttribute(attrs.sourceImg); if (typeof sourceImg === 'string' && element instanceof HTMLImageElement) { loadSourceImg(element, sourceImg, options, loadActions, errorActions); return; } // style="background-image: url(...)" var sourceBgImg = element.getAttribute(attrs.sourceBgImg); if (typeof sourceBgImg === 'string' && element instanceof HTMLElement) { loadSourceBgImg(element, sourceBgImg, options, loadActions, errorActions); return; } // iframe var sourceIframe = element.getAttribute(attrs.sourceIframe); if (typeof sourceIframe === 'string' && element instanceof HTMLPictureElement) { loadSourceIframe(element, sourceIframe, options, loadActions, errorActions); return; } // picture if (element instanceof HTMLPictureElement) { var img = element.querySelector('img'); if (img instanceof HTMLImageElement) { var sourceImg_1 = img.getAttribute(attrs.sourceImg); if (typeof sourceImg_1 === 'string') { loadSourcePicture( element, img, sourceImg_1, options, loadActions, errorActions ); return; } } } // container if (element.hasAttribute(attrs.sourceContainer)) { loadActions(); return; } console.log(element); console.log('▲ element has no zz-load source'); }; if (asPromise && window.Promise) { return new Promise(function (resolve, reject) { return load(resolve, reject); }); } else { return load( function () { return undefined; }, function () { return undefined; } ); } }