vue-lazyload.esm.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785
  1. /*!
  2. * Vue-Lazyload.js v1.3.5
  3. * (c) 2023 Awe <hilongjw@gmail.com>
  4. * Released under the MIT License.
  5. */
  6. function createCommonjsModule(fn, module) {
  7. return module = { exports: {} }, fn(module, module.exports), module.exports;
  8. }
  9. var assignSymbols$1 = createCommonjsModule(function (module) {
  10. var toString = Object.prototype.toString;
  11. var isEnumerable = Object.prototype.propertyIsEnumerable;
  12. var getSymbols = Object.getOwnPropertySymbols;
  13. module.exports = function (target) {
  14. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  15. args[_key - 1] = arguments[_key];
  16. }
  17. if (!isObject(target)) {
  18. throw new TypeError('expected the first argument to be an object');
  19. }
  20. if (args.length === 0 || typeof Symbol !== 'function' || typeof getSymbols !== 'function') {
  21. return target;
  22. }
  23. var _iteratorNormalCompletion = true;
  24. var _didIteratorError = false;
  25. var _iteratorError = undefined;
  26. try {
  27. for (var _iterator = args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  28. var arg = _step.value;
  29. var names = getSymbols(arg);
  30. var _iteratorNormalCompletion2 = true;
  31. var _didIteratorError2 = false;
  32. var _iteratorError2 = undefined;
  33. try {
  34. for (var _iterator2 = names[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  35. var key = _step2.value;
  36. if (isEnumerable.call(arg, key)) {
  37. target[key] = arg[key];
  38. }
  39. }
  40. } catch (err) {
  41. _didIteratorError2 = true;
  42. _iteratorError2 = err;
  43. } finally {
  44. try {
  45. if (!_iteratorNormalCompletion2 && _iterator2.return) {
  46. _iterator2.return();
  47. }
  48. } finally {
  49. if (_didIteratorError2) {
  50. throw _iteratorError2;
  51. }
  52. }
  53. }
  54. }
  55. } catch (err) {
  56. _didIteratorError = true;
  57. _iteratorError = err;
  58. } finally {
  59. try {
  60. if (!_iteratorNormalCompletion && _iterator.return) {
  61. _iterator.return();
  62. }
  63. } finally {
  64. if (_didIteratorError) {
  65. throw _iteratorError;
  66. }
  67. }
  68. }
  69. return target;
  70. };
  71. function isObject(val) {
  72. return typeof val === 'function' || toString.call(val) === '[object Object]' || Array.isArray(val);
  73. }
  74. });
  75. var assignSymbols$2 = /*#__PURE__*/Object.freeze({
  76. __proto__: null,
  77. 'default': assignSymbols$1,
  78. __moduleExports: assignSymbols$1
  79. });
  80. var assignSymbols = ( assignSymbols$2 && assignSymbols$1 ) || assignSymbols$2;
  81. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  82. return typeof obj;
  83. } : function (obj) {
  84. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  85. };
  86. var classCallCheck = function (instance, Constructor) {
  87. if (!(instance instanceof Constructor)) {
  88. throw new TypeError("Cannot call a class as a function");
  89. }
  90. };
  91. var createClass = function () {
  92. function defineProperties(target, props) {
  93. for (var i = 0; i < props.length; i++) {
  94. var descriptor = props[i];
  95. descriptor.enumerable = descriptor.enumerable || false;
  96. descriptor.configurable = true;
  97. if ("value" in descriptor) descriptor.writable = true;
  98. Object.defineProperty(target, descriptor.key, descriptor);
  99. }
  100. }
  101. return function (Constructor, protoProps, staticProps) {
  102. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  103. if (staticProps) defineProperties(Constructor, staticProps);
  104. return Constructor;
  105. };
  106. }();
  107. var assignDeep = createCommonjsModule(function (module) {
  108. var toString = Object.prototype.toString;
  109. var isValidKey = function isValidKey(key) {
  110. return key !== '__proto__' && key !== 'constructor' && key !== 'prototype';
  111. };
  112. var assign = module.exports = function (target) {
  113. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  114. args[_key - 1] = arguments[_key];
  115. }
  116. var i = 0;
  117. if (isPrimitive(target)) target = args[i++];
  118. if (!target) target = {};
  119. for (; i < args.length; i++) {
  120. if (isObject(args[i])) {
  121. var _iteratorNormalCompletion = true;
  122. var _didIteratorError = false;
  123. var _iteratorError = undefined;
  124. try {
  125. for (var _iterator = Object.keys(args[i])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  126. var key = _step.value;
  127. if (isValidKey(key)) {
  128. if (isObject(target[key]) && isObject(args[i][key])) {
  129. assign(target[key], args[i][key]);
  130. } else {
  131. target[key] = args[i][key];
  132. }
  133. }
  134. }
  135. } catch (err) {
  136. _didIteratorError = true;
  137. _iteratorError = err;
  138. } finally {
  139. try {
  140. if (!_iteratorNormalCompletion && _iterator.return) {
  141. _iterator.return();
  142. }
  143. } finally {
  144. if (_didIteratorError) {
  145. throw _iteratorError;
  146. }
  147. }
  148. }
  149. assignSymbols(target, args[i]);
  150. }
  151. }
  152. return target;
  153. };
  154. function isObject(val) {
  155. return typeof val === 'function' || toString.call(val) === '[object Object]';
  156. }
  157. function isPrimitive(val) {
  158. return (typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object' ? val === null : typeof val !== 'function';
  159. }
  160. });
  161. var inBrowser = typeof window !== 'undefined' && window !== null;
  162. var hasIntersectionObserver = checkIntersectionObserver();
  163. function checkIntersectionObserver() {
  164. if (inBrowser && 'IntersectionObserver' in window && 'IntersectionObserverEntry' in window && 'intersectionRatio' in window.IntersectionObserverEntry.prototype) {
  165. // Minimal polyfill for Edge 15's lack of `isIntersecting`
  166. // See: https://github.com/w3c/IntersectionObserver/issues/211
  167. if (!('isIntersecting' in window.IntersectionObserverEntry.prototype)) {
  168. Object.defineProperty(window.IntersectionObserverEntry.prototype, 'isIntersecting', {
  169. get: function get() {
  170. return this.intersectionRatio > 0;
  171. }
  172. });
  173. }
  174. return true;
  175. }
  176. return false;
  177. }
  178. var modeType = {
  179. event: 'event',
  180. observer: 'observer'
  181. // CustomEvent polyfill for IE
  182. };var CustomEvent = function () {
  183. if (!inBrowser) return;
  184. // not IE
  185. if (typeof window.CustomEvent === 'function') return window.CustomEvent;
  186. function CustomEvent(event, params) {
  187. params = params || { bubbles: false, cancelable: false, detail: undefined };
  188. var evt = document.createEvent('CustomEvent');
  189. evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
  190. return evt;
  191. }
  192. CustomEvent.prototype = window.Event.prototype;
  193. return CustomEvent;
  194. }();
  195. function remove(arr, item) {
  196. if (!arr.length) return;
  197. var index = arr.indexOf(item);
  198. if (index > -1) return arr.splice(index, 1);
  199. }
  200. function some(arr, fn) {
  201. var has = false;
  202. for (var i = 0, len = arr.length; i < len; i++) {
  203. if (fn(arr[i])) {
  204. has = true;
  205. break;
  206. }
  207. }
  208. return has;
  209. }
  210. function getBestSelectionFromSrcset(el, scale) {
  211. if (el.tagName !== 'IMG' || !el.getAttribute('data-srcset')) return;
  212. var options = el.getAttribute('data-srcset');
  213. var result = [];
  214. var container = el.parentNode;
  215. var containerWidth = container.offsetWidth * scale;
  216. var spaceIndex = void 0;
  217. var tmpSrc = void 0;
  218. var tmpWidth = void 0;
  219. options = options.trim().split(',');
  220. options.map(function (item) {
  221. item = item.trim();
  222. spaceIndex = item.lastIndexOf(' ');
  223. if (spaceIndex === -1) {
  224. tmpSrc = item;
  225. tmpWidth = 999998;
  226. } else {
  227. tmpSrc = item.substr(0, spaceIndex);
  228. tmpWidth = parseInt(item.substr(spaceIndex + 1, item.length - spaceIndex - 2), 10);
  229. }
  230. result.push([tmpWidth, tmpSrc]);
  231. });
  232. result.sort(function (a, b) {
  233. if (a[0] < b[0]) {
  234. return 1;
  235. }
  236. if (a[0] > b[0]) {
  237. return -1;
  238. }
  239. if (a[0] === b[0]) {
  240. if (b[1].indexOf('.webp', b[1].length - 5) !== -1) {
  241. return 1;
  242. }
  243. if (a[1].indexOf('.webp', a[1].length - 5) !== -1) {
  244. return -1;
  245. }
  246. }
  247. return 0;
  248. });
  249. var bestSelectedSrc = '';
  250. var tmpOption = void 0;
  251. for (var i = 0; i < result.length; i++) {
  252. tmpOption = result[i];
  253. bestSelectedSrc = tmpOption[1];
  254. var next = result[i + 1];
  255. if (next && next[0] < containerWidth) {
  256. bestSelectedSrc = tmpOption[1];
  257. break;
  258. } else if (!next) {
  259. bestSelectedSrc = tmpOption[1];
  260. break;
  261. }
  262. }
  263. return bestSelectedSrc;
  264. }
  265. function find(arr, fn) {
  266. var item = void 0;
  267. for (var i = 0, len = arr.length; i < len; i++) {
  268. if (fn(arr[i])) {
  269. item = arr[i];
  270. break;
  271. }
  272. }
  273. return item;
  274. }
  275. var getDPR = function getDPR() {
  276. var scale = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
  277. return inBrowser ? window.devicePixelRatio || scale : scale;
  278. };
  279. function supportWebp() {
  280. if (!inBrowser) return false;
  281. var support = true;
  282. try {
  283. var elem = document.createElement('canvas');
  284. if (elem.getContext && elem.getContext('2d')) {
  285. support = elem.toDataURL('image/webp').indexOf('data:image/webp') === 0;
  286. }
  287. } catch (err) {
  288. support = false;
  289. }
  290. return support;
  291. }
  292. function throttle(action, delay) {
  293. var timeout = null;
  294. var movement = null;
  295. var lastRun = 0;
  296. var needRun = false;
  297. return function () {
  298. needRun = true;
  299. if (timeout) {
  300. return;
  301. }
  302. var elapsed = Date.now() - lastRun;
  303. var context = this;
  304. var args = arguments;
  305. var runCallback = function runCallback() {
  306. lastRun = Date.now();
  307. timeout = false;
  308. action.apply(context, args);
  309. };
  310. if (elapsed >= delay) {
  311. runCallback();
  312. } else {
  313. timeout = setTimeout(runCallback, delay);
  314. }
  315. if (needRun) {
  316. clearTimeout(movement);
  317. movement = setTimeout(runCallback, 2 * delay);
  318. }
  319. };
  320. }
  321. function testSupportsPassive() {
  322. if (!inBrowser) return;
  323. var support = false;
  324. try {
  325. var opts = Object.defineProperty({}, 'passive', {
  326. get: function get() {
  327. support = true;
  328. }
  329. });
  330. window.addEventListener('test', null, opts);
  331. } catch (e) {}
  332. return support;
  333. }
  334. var supportsPassive = testSupportsPassive();
  335. var _ = {
  336. on: function on(el, type, func) {
  337. var capture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  338. if (supportsPassive) {
  339. el.addEventListener(type, func, {
  340. capture: capture,
  341. passive: true
  342. });
  343. } else {
  344. el.addEventListener(type, func, capture);
  345. }
  346. },
  347. off: function off(el, type, func) {
  348. var capture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  349. el.removeEventListener(type, func, capture);
  350. }
  351. };
  352. var loadImageAsync = function loadImageAsync(item, resolve, reject) {
  353. var image = new Image();
  354. if (!item || !item.src) {
  355. var err = new Error('image src is required');
  356. return reject(err);
  357. }
  358. image.src = item.src;
  359. if (item.cors) {
  360. image.crossOrigin = item.cors;
  361. }
  362. image.onload = function () {
  363. resolve({
  364. naturalHeight: image.naturalHeight,
  365. naturalWidth: image.naturalWidth,
  366. src: image.src
  367. });
  368. };
  369. image.onerror = function (e) {
  370. reject(e);
  371. };
  372. };
  373. var style = function style(el, prop) {
  374. return typeof getComputedStyle !== 'undefined' ? getComputedStyle(el, null).getPropertyValue(prop) : el.style[prop];
  375. };
  376. var overflow = function overflow(el) {
  377. return style(el, 'overflow') + style(el, 'overflow-y') + style(el, 'overflow-x');
  378. };
  379. var scrollParent = function scrollParent(el) {
  380. if (!inBrowser) return;
  381. if (!(el instanceof HTMLElement)) {
  382. return window;
  383. }
  384. var parent = el;
  385. while (parent) {
  386. if (parent === document.body || parent === document.documentElement) {
  387. break;
  388. }
  389. if (!parent.parentNode) {
  390. break;
  391. }
  392. if (/(scroll|auto)/.test(overflow(parent))) {
  393. return parent;
  394. }
  395. parent = parent.parentNode;
  396. }
  397. return window;
  398. };
  399. function isObject(obj) {
  400. return obj !== null && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object';
  401. }
  402. function ObjectKeys(obj) {
  403. if (!(obj instanceof Object)) return [];
  404. if (Object.keys) {
  405. return Object.keys(obj);
  406. } else {
  407. var keys = [];
  408. for (var key in obj) {
  409. if (obj.hasOwnProperty(key)) {
  410. keys.push(key);
  411. }
  412. }
  413. return keys;
  414. }
  415. }
  416. function ArrayFrom(arrLike) {
  417. var len = arrLike.length;
  418. var list = [];
  419. for (var i = 0; i < len; i++) {
  420. list.push(arrLike[i]);
  421. }
  422. return list;
  423. }
  424. function noop() {}
  425. var ImageCache = function () {
  426. function ImageCache(_ref) {
  427. var max = _ref.max;
  428. classCallCheck(this, ImageCache);
  429. this.options = {
  430. max: max || 100
  431. };
  432. this._caches = [];
  433. }
  434. createClass(ImageCache, [{
  435. key: 'has',
  436. value: function has(key) {
  437. return this._caches.indexOf(key) > -1;
  438. }
  439. }, {
  440. key: 'add',
  441. value: function add(key) {
  442. if (this.has(key)) return;
  443. this._caches.push(key);
  444. if (this._caches.length > this.options.max) {
  445. this.free();
  446. }
  447. }
  448. }, {
  449. key: 'free',
  450. value: function free() {
  451. this._caches.shift();
  452. }
  453. }]);
  454. return ImageCache;
  455. }();
  456. // el: {
  457. // state,
  458. // src,
  459. // error,
  460. // loading
  461. // }
  462. var ReactiveListener = function () {
  463. function ReactiveListener(_ref) {
  464. var el = _ref.el,
  465. src = _ref.src,
  466. error = _ref.error,
  467. loading = _ref.loading,
  468. bindType = _ref.bindType,
  469. $parent = _ref.$parent,
  470. options = _ref.options,
  471. cors = _ref.cors,
  472. elRenderer = _ref.elRenderer,
  473. imageCache = _ref.imageCache;
  474. classCallCheck(this, ReactiveListener);
  475. this.el = el;
  476. this.src = src;
  477. this.error = error;
  478. this.loading = loading;
  479. this.bindType = bindType;
  480. this.attempt = 0;
  481. this.cors = cors;
  482. this.naturalHeight = 0;
  483. this.naturalWidth = 0;
  484. this.options = options;
  485. this.rect = null;
  486. this.$parent = $parent;
  487. this.elRenderer = elRenderer;
  488. this._imageCache = imageCache;
  489. this.performanceData = {
  490. init: Date.now(),
  491. loadStart: 0,
  492. loadEnd: 0
  493. };
  494. this.filter();
  495. this.initState();
  496. this.render('loading', false);
  497. }
  498. /*
  499. * init listener state
  500. * @return
  501. */
  502. createClass(ReactiveListener, [{
  503. key: 'initState',
  504. value: function initState() {
  505. if ('dataset' in this.el) {
  506. this.el.dataset.src = this.src;
  507. } else {
  508. this.el.setAttribute('data-src', this.src);
  509. }
  510. this.state = {
  511. loading: false,
  512. error: false,
  513. loaded: false,
  514. rendered: false
  515. };
  516. }
  517. /*
  518. * record performance
  519. * @return
  520. */
  521. }, {
  522. key: 'record',
  523. value: function record(event) {
  524. this.performanceData[event] = Date.now();
  525. }
  526. /*
  527. * update image listener data
  528. * @param {String} image uri
  529. * @param {String} loading image uri
  530. * @param {String} error image uri
  531. * @return
  532. */
  533. }, {
  534. key: 'update',
  535. value: function update(_ref2) {
  536. var src = _ref2.src,
  537. loading = _ref2.loading,
  538. error = _ref2.error;
  539. var oldSrc = this.src;
  540. this.src = src;
  541. this.loading = loading;
  542. this.error = error;
  543. this.filter();
  544. if (oldSrc !== this.src) {
  545. this.attempt = 0;
  546. this.initState();
  547. }
  548. }
  549. /*
  550. * get el node rect
  551. * @return
  552. */
  553. }, {
  554. key: 'getRect',
  555. value: function getRect() {
  556. this.rect = this.el.getBoundingClientRect();
  557. }
  558. /*
  559. * check el is in view
  560. * @return {Boolean} el is in view
  561. */
  562. }, {
  563. key: 'checkInView',
  564. value: function checkInView() {
  565. this.getRect();
  566. return this.rect.top < window.innerHeight * this.options.preLoad && this.rect.bottom > this.options.preLoadTop && this.rect.left < window.innerWidth * this.options.preLoad && this.rect.right > 0;
  567. }
  568. /*
  569. * listener filter
  570. */
  571. }, {
  572. key: 'filter',
  573. value: function filter() {
  574. var _this = this;
  575. ObjectKeys(this.options.filter).map(function (key) {
  576. _this.options.filter[key](_this, _this.options);
  577. });
  578. }
  579. /*
  580. * render loading first
  581. * @params cb:Function
  582. * @return
  583. */
  584. }, {
  585. key: 'renderLoading',
  586. value: function renderLoading(cb) {
  587. var _this2 = this;
  588. this.state.loading = true;
  589. loadImageAsync({
  590. src: this.loading,
  591. cors: this.cors
  592. }, function (data) {
  593. _this2.render('loading', false);
  594. _this2.state.loading = false;
  595. cb();
  596. }, function () {
  597. // handler `loading image` load failed
  598. cb();
  599. _this2.state.loading = false;
  600. if (!_this2.options.silent) console.warn('VueLazyload log: load failed with loading image(' + _this2.loading + ')');
  601. });
  602. }
  603. /*
  604. * try load image and render it
  605. * @return
  606. */
  607. }, {
  608. key: 'load',
  609. value: function load() {
  610. var _this3 = this;
  611. var onFinish = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : noop;
  612. if (this.attempt > this.options.attempt - 1 && this.state.error) {
  613. if (!this.options.silent) console.log('VueLazyload log: ' + this.src + ' tried too more than ' + this.options.attempt + ' times');
  614. onFinish();
  615. return;
  616. }
  617. if (this.state.rendered && this.state.loaded) return;
  618. if (this._imageCache.has(this.src)) {
  619. this.state.loaded = true;
  620. this.render('loaded', true);
  621. this.state.rendered = true;
  622. return onFinish();
  623. }
  624. this.renderLoading(function () {
  625. _this3.attempt++;
  626. _this3.options.adapter['beforeLoad'] && _this3.options.adapter['beforeLoad'](_this3, _this3.options);
  627. _this3.record('loadStart');
  628. loadImageAsync({
  629. src: _this3.src,
  630. cors: _this3.cors
  631. }, function (data) {
  632. _this3.naturalHeight = data.naturalHeight;
  633. _this3.naturalWidth = data.naturalWidth;
  634. _this3.state.loaded = true;
  635. _this3.state.error = false;
  636. _this3.record('loadEnd');
  637. _this3.render('loaded', false);
  638. _this3.state.rendered = true;
  639. _this3._imageCache.add(_this3.src);
  640. onFinish();
  641. }, function (err) {
  642. !_this3.options.silent && console.error(err);
  643. _this3.state.error = true;
  644. _this3.state.loaded = false;
  645. _this3.render('error', false);
  646. });
  647. });
  648. }
  649. /*
  650. * render image
  651. * @param {String} state to render // ['loading', 'src', 'error']
  652. * @param {String} is form cache
  653. * @return
  654. */
  655. }, {
  656. key: 'render',
  657. value: function render(state, cache) {
  658. this.elRenderer(this, state, cache);
  659. }
  660. /*
  661. * output performance data
  662. * @return {Object} performance data
  663. */
  664. }, {
  665. key: 'performance',
  666. value: function performance() {
  667. var state = 'loading';
  668. var time = 0;
  669. if (this.state.loaded) {
  670. state = 'loaded';
  671. time = (this.performanceData.loadEnd - this.performanceData.loadStart) / 1000;
  672. }
  673. if (this.state.error) state = 'error';
  674. return {
  675. src: this.src,
  676. state: state,
  677. time: time
  678. };
  679. }
  680. /*
  681. * $destroy
  682. * @return
  683. */
  684. }, {
  685. key: '$destroy',
  686. value: function $destroy() {
  687. this.el = null;
  688. this.src = null;
  689. this.error = null;
  690. this.loading = null;
  691. this.bindType = null;
  692. this.attempt = 0;
  693. }
  694. }]);
  695. return ReactiveListener;
  696. }();
  697. var DEFAULT_URL = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
  698. var DEFAULT_EVENTS = ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend', 'touchmove'];
  699. var DEFAULT_OBSERVER_OPTIONS = {
  700. rootMargin: '0px',
  701. threshold: 0
  702. };
  703. function Lazy(Vue) {
  704. return function () {
  705. function Lazy(_ref) {
  706. var preLoad = _ref.preLoad,
  707. error = _ref.error,
  708. throttleWait = _ref.throttleWait,
  709. preLoadTop = _ref.preLoadTop,
  710. dispatchEvent = _ref.dispatchEvent,
  711. loading = _ref.loading,
  712. attempt = _ref.attempt,
  713. _ref$silent = _ref.silent,
  714. silent = _ref$silent === undefined ? true : _ref$silent,
  715. scale = _ref.scale,
  716. listenEvents = _ref.listenEvents;
  717. _ref.hasbind;
  718. var filter = _ref.filter,
  719. adapter = _ref.adapter,
  720. observer = _ref.observer,
  721. observerOptions = _ref.observerOptions;
  722. classCallCheck(this, Lazy);
  723. this.version = '"1.3.5"';
  724. this.mode = modeType.event;
  725. this.ListenerQueue = [];
  726. this.TargetIndex = 0;
  727. this.TargetQueue = [];
  728. this.options = {
  729. silent: silent,
  730. dispatchEvent: !!dispatchEvent,
  731. throttleWait: throttleWait || 200,
  732. preLoad: preLoad || 1.3,
  733. preLoadTop: preLoadTop || 0,
  734. error: error || DEFAULT_URL,
  735. loading: loading || DEFAULT_URL,
  736. attempt: attempt || 3,
  737. scale: scale || getDPR(scale),
  738. ListenEvents: listenEvents || DEFAULT_EVENTS,
  739. hasbind: false,
  740. supportWebp: supportWebp(),
  741. filter: filter || {},
  742. adapter: adapter || {},
  743. observer: !!observer,
  744. observerOptions: observerOptions || DEFAULT_OBSERVER_OPTIONS
  745. };
  746. this._initEvent();
  747. this._imageCache = new ImageCache({ max: 200 });
  748. this.lazyLoadHandler = throttle(this._lazyLoadHandler.bind(this), this.options.throttleWait);
  749. this.setMode(this.options.observer ? modeType.observer : modeType.event);
  750. }
  751. /**
  752. * update config
  753. * @param {Object} config params
  754. * @return
  755. */
  756. createClass(Lazy, [{
  757. key: 'config',
  758. value: function config() {
  759. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  760. assignDeep(this.options, options);
  761. }
  762. /**
  763. * output listener's load performance
  764. * @return {Array}
  765. */
  766. }, {
  767. key: 'performance',
  768. value: function performance() {
  769. var list = [];
  770. this.ListenerQueue.map(function (item) {
  771. list.push(item.performance());
  772. });
  773. return list;
  774. }
  775. /*
  776. * add lazy component to queue
  777. * @param {Vue} vm lazy component instance
  778. * @return
  779. */
  780. }, {
  781. key: 'addLazyBox',
  782. value: function addLazyBox(vm) {
  783. this.ListenerQueue.push(vm);
  784. if (inBrowser) {
  785. this._addListenerTarget(window);
  786. this._observer && this._observer.observe(vm.el);
  787. if (vm.$el && vm.$el.parentNode) {
  788. this._addListenerTarget(vm.$el.parentNode);
  789. }
  790. }
  791. }
  792. /*
  793. * add image listener to queue
  794. * @param {DOM} el
  795. * @param {object} binding vue directive binding
  796. * @param {vnode} vnode vue directive vnode
  797. * @return
  798. */
  799. }, {
  800. key: 'add',
  801. value: function add(el, binding, vnode) {
  802. var _this = this;
  803. if (some(this.ListenerQueue, function (item) {
  804. return item.el === el;
  805. })) {
  806. this.update(el, binding);
  807. return Vue.nextTick(this.lazyLoadHandler);
  808. }
  809. var _valueFormatter2 = this._valueFormatter(binding.value),
  810. src = _valueFormatter2.src,
  811. loading = _valueFormatter2.loading,
  812. error = _valueFormatter2.error,
  813. cors = _valueFormatter2.cors;
  814. Vue.nextTick(function () {
  815. src = getBestSelectionFromSrcset(el, _this.options.scale) || src;
  816. _this._observer && _this._observer.observe(el);
  817. var container = Object.keys(binding.modifiers)[0];
  818. var $parent = void 0;
  819. if (container) {
  820. $parent = vnode.context.$refs[container];
  821. // if there is container passed in, try ref first, then fallback to getElementById to support the original usage
  822. $parent = $parent ? $parent.$el || $parent : document.getElementById(container);
  823. }
  824. if (!$parent) {
  825. $parent = scrollParent(el);
  826. }
  827. var newListener = new ReactiveListener({
  828. bindType: binding.arg,
  829. $parent: $parent,
  830. el: el,
  831. loading: loading,
  832. error: error,
  833. src: src,
  834. cors: cors,
  835. elRenderer: _this._elRenderer.bind(_this),
  836. options: _this.options,
  837. imageCache: _this._imageCache
  838. });
  839. _this.ListenerQueue.push(newListener);
  840. if (inBrowser) {
  841. _this._addListenerTarget(window);
  842. _this._addListenerTarget($parent);
  843. }
  844. _this.lazyLoadHandler();
  845. Vue.nextTick(function () {
  846. return _this.lazyLoadHandler();
  847. });
  848. });
  849. }
  850. /**
  851. * update image src
  852. * @param {DOM} el
  853. * @param {object} vue directive binding
  854. * @return
  855. */
  856. }, {
  857. key: 'update',
  858. value: function update(el, binding, vnode) {
  859. var _this2 = this;
  860. var _valueFormatter3 = this._valueFormatter(binding.value),
  861. src = _valueFormatter3.src,
  862. loading = _valueFormatter3.loading,
  863. error = _valueFormatter3.error;
  864. src = getBestSelectionFromSrcset(el, this.options.scale) || src;
  865. var exist = find(this.ListenerQueue, function (item) {
  866. return item.el === el;
  867. });
  868. if (!exist) {
  869. this.add(el, binding, vnode);
  870. } else {
  871. exist.update({
  872. src: src,
  873. loading: loading,
  874. error: error
  875. });
  876. }
  877. if (this._observer) {
  878. this._observer.unobserve(el);
  879. this._observer.observe(el);
  880. }
  881. this.lazyLoadHandler();
  882. Vue.nextTick(function () {
  883. return _this2.lazyLoadHandler();
  884. });
  885. }
  886. /**
  887. * remove listener form list
  888. * @param {DOM} el
  889. * @return
  890. */
  891. }, {
  892. key: 'remove',
  893. value: function remove$1(el) {
  894. if (!el) return;
  895. this._observer && this._observer.unobserve(el);
  896. var existItem = find(this.ListenerQueue, function (item) {
  897. return item.el === el;
  898. });
  899. if (existItem) {
  900. this._removeListenerTarget(existItem.$parent);
  901. this._removeListenerTarget(window);
  902. remove(this.ListenerQueue, existItem);
  903. existItem.$destroy();
  904. }
  905. }
  906. /*
  907. * remove lazy components form list
  908. * @param {Vue} vm Vue instance
  909. * @return
  910. */
  911. }, {
  912. key: 'removeComponent',
  913. value: function removeComponent(vm) {
  914. if (!vm) return;
  915. remove(this.ListenerQueue, vm);
  916. this._observer && this._observer.unobserve(vm.el);
  917. if (vm.$parent && vm.$el.parentNode) {
  918. this._removeListenerTarget(vm.$el.parentNode);
  919. }
  920. this._removeListenerTarget(window);
  921. }
  922. }, {
  923. key: 'setMode',
  924. value: function setMode(mode) {
  925. var _this3 = this;
  926. if (!hasIntersectionObserver && mode === modeType.observer) {
  927. mode = modeType.event;
  928. }
  929. this.mode = mode; // event or observer
  930. if (mode === modeType.event) {
  931. if (this._observer) {
  932. this.ListenerQueue.forEach(function (listener) {
  933. _this3._observer.unobserve(listener.el);
  934. });
  935. this._observer = null;
  936. }
  937. this.TargetQueue.forEach(function (target) {
  938. _this3._initListen(target.el, true);
  939. });
  940. } else {
  941. this.TargetQueue.forEach(function (target) {
  942. _this3._initListen(target.el, false);
  943. });
  944. this._initIntersectionObserver();
  945. }
  946. }
  947. /*
  948. *** Private functions ***
  949. */
  950. /*
  951. * add listener target
  952. * @param {DOM} el listener target
  953. * @return
  954. */
  955. }, {
  956. key: '_addListenerTarget',
  957. value: function _addListenerTarget(el) {
  958. if (!el) return;
  959. var target = find(this.TargetQueue, function (target) {
  960. return target.el === el;
  961. });
  962. if (!target) {
  963. target = {
  964. el: el,
  965. id: ++this.TargetIndex,
  966. childrenCount: 1,
  967. listened: true
  968. };
  969. this.mode === modeType.event && this._initListen(target.el, true);
  970. this.TargetQueue.push(target);
  971. } else {
  972. target.childrenCount++;
  973. }
  974. return this.TargetIndex;
  975. }
  976. /*
  977. * remove listener target or reduce target childrenCount
  978. * @param {DOM} el or window
  979. * @return
  980. */
  981. }, {
  982. key: '_removeListenerTarget',
  983. value: function _removeListenerTarget(el) {
  984. var _this4 = this;
  985. this.TargetQueue.forEach(function (target, index) {
  986. if (target.el === el) {
  987. target.childrenCount--;
  988. if (!target.childrenCount) {
  989. _this4._initListen(target.el, false);
  990. _this4.TargetQueue.splice(index, 1);
  991. target = null;
  992. }
  993. }
  994. });
  995. }
  996. /*
  997. * add or remove eventlistener
  998. * @param {DOM} el DOM or Window
  999. * @param {boolean} start flag
  1000. * @return
  1001. */
  1002. }, {
  1003. key: '_initListen',
  1004. value: function _initListen(el, start) {
  1005. var _this5 = this;
  1006. this.options.ListenEvents.forEach(function (evt) {
  1007. return _[start ? 'on' : 'off'](el, evt, _this5.lazyLoadHandler);
  1008. });
  1009. }
  1010. }, {
  1011. key: '_initEvent',
  1012. value: function _initEvent() {
  1013. var _this6 = this;
  1014. this.Event = {
  1015. listeners: {
  1016. loading: [],
  1017. loaded: [],
  1018. error: []
  1019. }
  1020. };
  1021. this.$on = function (event, func) {
  1022. if (!_this6.Event.listeners[event]) _this6.Event.listeners[event] = [];
  1023. _this6.Event.listeners[event].push(func);
  1024. };
  1025. this.$once = function (event, func) {
  1026. var vm = _this6;
  1027. function on() {
  1028. vm.$off(event, on);
  1029. func.apply(vm, arguments);
  1030. }
  1031. _this6.$on(event, on);
  1032. };
  1033. this.$off = function (event, func) {
  1034. if (!func) {
  1035. if (!_this6.Event.listeners[event]) return;
  1036. _this6.Event.listeners[event].length = 0;
  1037. return;
  1038. }
  1039. remove(_this6.Event.listeners[event], func);
  1040. };
  1041. this.$emit = function (event, context, inCache) {
  1042. if (!_this6.Event.listeners[event]) return;
  1043. _this6.Event.listeners[event].forEach(function (func) {
  1044. return func(context, inCache);
  1045. });
  1046. };
  1047. }
  1048. /**
  1049. * find nodes which in viewport and trigger load
  1050. * @return
  1051. */
  1052. }, {
  1053. key: '_lazyLoadHandler',
  1054. value: function _lazyLoadHandler() {
  1055. var _this7 = this;
  1056. var freeList = [];
  1057. this.ListenerQueue.forEach(function (listener, index) {
  1058. if (!listener.el || !listener.el.parentNode) {
  1059. freeList.push(listener);
  1060. }
  1061. var catIn = listener.checkInView();
  1062. if (!catIn) return;
  1063. listener.load();
  1064. });
  1065. freeList.forEach(function (item) {
  1066. remove(_this7.ListenerQueue, item);
  1067. item.$destroy();
  1068. });
  1069. }
  1070. /**
  1071. * init IntersectionObserver
  1072. * set mode to observer
  1073. * @return
  1074. */
  1075. }, {
  1076. key: '_initIntersectionObserver',
  1077. value: function _initIntersectionObserver() {
  1078. var _this8 = this;
  1079. if (!hasIntersectionObserver) return;
  1080. this._observer = new IntersectionObserver(this._observerHandler.bind(this), this.options.observerOptions);
  1081. if (this.ListenerQueue.length) {
  1082. this.ListenerQueue.forEach(function (listener) {
  1083. _this8._observer.observe(listener.el);
  1084. });
  1085. }
  1086. }
  1087. /**
  1088. * init IntersectionObserver
  1089. * @return
  1090. */
  1091. }, {
  1092. key: '_observerHandler',
  1093. value: function _observerHandler(entries, observer) {
  1094. var _this9 = this;
  1095. entries.forEach(function (entry) {
  1096. if (entry.isIntersecting) {
  1097. _this9.ListenerQueue.forEach(function (listener) {
  1098. if (listener.el === entry.target) {
  1099. if (listener.state.loaded) return _this9._observer.unobserve(listener.el);
  1100. listener.load();
  1101. }
  1102. });
  1103. }
  1104. });
  1105. }
  1106. /**
  1107. * set element attribute with image'url and state
  1108. * @param {object} lazyload listener object
  1109. * @param {string} state will be rendered
  1110. * @param {bool} inCache is rendered from cache
  1111. * @return
  1112. */
  1113. }, {
  1114. key: '_elRenderer',
  1115. value: function _elRenderer(listener, state, cache) {
  1116. if (!listener.el) return;
  1117. var el = listener.el,
  1118. bindType = listener.bindType;
  1119. var src = void 0;
  1120. switch (state) {
  1121. case 'loading':
  1122. src = listener.loading;
  1123. break;
  1124. case 'error':
  1125. src = listener.error;
  1126. break;
  1127. default:
  1128. src = listener.src;
  1129. break;
  1130. }
  1131. if (bindType) {
  1132. el.style[bindType] = 'url("' + src + '")';
  1133. } else if (el.getAttribute('src') !== src) {
  1134. el.setAttribute('src', src);
  1135. }
  1136. el.setAttribute('lazy', state);
  1137. this.$emit(state, listener, cache);
  1138. this.options.adapter[state] && this.options.adapter[state](listener, this.options);
  1139. if (this.options.dispatchEvent) {
  1140. var event = new CustomEvent(state, {
  1141. detail: listener
  1142. });
  1143. el.dispatchEvent(event);
  1144. }
  1145. }
  1146. /**
  1147. * generate loading loaded error image url
  1148. * @param {string} image's src
  1149. * @return {object} image's loading, loaded, error url
  1150. */
  1151. }, {
  1152. key: '_valueFormatter',
  1153. value: function _valueFormatter(value) {
  1154. var src = value;
  1155. var loading = this.options.loading;
  1156. var error = this.options.error;
  1157. // value is object
  1158. if (isObject(value)) {
  1159. if (!value.src && !this.options.silent) console.error('Vue Lazyload warning: miss src with ' + value);
  1160. src = value.src;
  1161. loading = value.loading || this.options.loading;
  1162. error = value.error || this.options.error;
  1163. }
  1164. return {
  1165. src: src,
  1166. loading: loading,
  1167. error: error
  1168. };
  1169. }
  1170. }]);
  1171. return Lazy;
  1172. }();
  1173. }
  1174. Lazy.install = function (Vue) {
  1175. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1176. var LazyClass = Lazy(Vue);
  1177. var lazy = new LazyClass(options);
  1178. var isVue2 = Vue.version.split('.')[0] === '2';
  1179. if (isVue2) {
  1180. Vue.directive('lazy', {
  1181. bind: lazy.add.bind(lazy),
  1182. update: lazy.update.bind(lazy),
  1183. componentUpdated: lazy.lazyLoadHandler.bind(lazy),
  1184. unbind: lazy.remove.bind(lazy)
  1185. });
  1186. } else {
  1187. Vue.directive('lazy', {
  1188. bind: lazy.lazyLoadHandler.bind(lazy),
  1189. update: function update(newValue, oldValue) {
  1190. assignDeep(this.vm.$refs, this.vm.$els);
  1191. lazy.add(this.el, {
  1192. modifiers: this.modifiers || {},
  1193. arg: this.arg,
  1194. value: newValue,
  1195. oldValue: oldValue
  1196. }, {
  1197. context: this.vm
  1198. });
  1199. },
  1200. unbind: function unbind() {
  1201. lazy.remove(this.el);
  1202. }
  1203. });
  1204. }
  1205. };
  1206. var LazyComponent = function LazyComponent(lazy) {
  1207. return {
  1208. props: {
  1209. tag: {
  1210. type: String,
  1211. default: 'div'
  1212. }
  1213. },
  1214. render: function render(h) {
  1215. return h(this.tag, null, this.show ? this.$slots.default : null);
  1216. },
  1217. data: function data() {
  1218. return {
  1219. el: null,
  1220. state: {
  1221. loaded: false
  1222. },
  1223. rect: {},
  1224. show: false
  1225. };
  1226. },
  1227. mounted: function mounted() {
  1228. this.el = this.$el;
  1229. lazy.addLazyBox(this);
  1230. lazy.lazyLoadHandler();
  1231. },
  1232. beforeDestroy: function beforeDestroy() {
  1233. lazy.removeComponent(this);
  1234. },
  1235. methods: {
  1236. getRect: function getRect() {
  1237. this.rect = this.$el.getBoundingClientRect();
  1238. },
  1239. checkInView: function checkInView() {
  1240. this.getRect();
  1241. return inBrowser && this.rect.top < window.innerHeight * lazy.options.preLoad && this.rect.bottom > 0 && this.rect.left < window.innerWidth * lazy.options.preLoad && this.rect.right > 0;
  1242. },
  1243. load: function load() {
  1244. this.show = true;
  1245. this.state.loaded = true;
  1246. this.$emit('show', this);
  1247. },
  1248. destroy: function destroy() {
  1249. return this.$destroy;
  1250. }
  1251. }
  1252. };
  1253. };
  1254. LazyComponent.install = function (Vue) {
  1255. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1256. var LazyClass = Lazy(Vue);
  1257. var lazy = new LazyClass(options);
  1258. Vue.component('lazy-component', LazyComponent(lazy));
  1259. };
  1260. var LazyContainerMananger = function () {
  1261. function LazyContainerMananger(_ref) {
  1262. var lazy = _ref.lazy;
  1263. classCallCheck(this, LazyContainerMananger);
  1264. this.lazy = lazy;
  1265. lazy.lazyContainerMananger = this;
  1266. this._queue = [];
  1267. }
  1268. createClass(LazyContainerMananger, [{
  1269. key: 'bind',
  1270. value: function bind(el, binding, vnode) {
  1271. var container = new LazyContainer({ el: el, binding: binding, vnode: vnode, lazy: this.lazy });
  1272. this._queue.push(container);
  1273. }
  1274. }, {
  1275. key: 'update',
  1276. value: function update(el, binding, vnode) {
  1277. var container = find(this._queue, function (item) {
  1278. return item.el === el;
  1279. });
  1280. if (!container) return;
  1281. container.update({ el: el, binding: binding, vnode: vnode });
  1282. }
  1283. }, {
  1284. key: 'unbind',
  1285. value: function unbind(el, binding, vnode) {
  1286. var container = find(this._queue, function (item) {
  1287. return item.el === el;
  1288. });
  1289. if (!container) return;
  1290. container.clear();
  1291. remove(this._queue, container);
  1292. }
  1293. }]);
  1294. return LazyContainerMananger;
  1295. }();
  1296. var defaultOptions = {
  1297. selector: 'img'
  1298. };
  1299. var LazyContainer = function () {
  1300. function LazyContainer(_ref2) {
  1301. var el = _ref2.el,
  1302. binding = _ref2.binding,
  1303. vnode = _ref2.vnode,
  1304. lazy = _ref2.lazy;
  1305. classCallCheck(this, LazyContainer);
  1306. this.el = null;
  1307. this.vnode = vnode;
  1308. this.binding = binding;
  1309. this.options = {};
  1310. this.lazy = lazy;
  1311. this._queue = [];
  1312. this.update({ el: el, binding: binding });
  1313. }
  1314. createClass(LazyContainer, [{
  1315. key: 'update',
  1316. value: function update(_ref3) {
  1317. var _this = this;
  1318. var el = _ref3.el,
  1319. binding = _ref3.binding;
  1320. this.el = el;
  1321. this.options = assignDeep({}, defaultOptions, binding.value);
  1322. var imgs = this.getImgs();
  1323. imgs.forEach(function (el) {
  1324. _this.lazy.add(el, assignDeep({}, _this.binding, {
  1325. value: {
  1326. src: 'dataset' in el ? el.dataset.src : el.getAttribute('data-src'),
  1327. error: ('dataset' in el ? el.dataset.error : el.getAttribute('data-error')) || _this.options.error,
  1328. loading: ('dataset' in el ? el.dataset.loading : el.getAttribute('data-loading')) || _this.options.loading
  1329. }
  1330. }), _this.vnode);
  1331. });
  1332. }
  1333. }, {
  1334. key: 'getImgs',
  1335. value: function getImgs() {
  1336. return ArrayFrom(this.el.querySelectorAll(this.options.selector));
  1337. }
  1338. }, {
  1339. key: 'clear',
  1340. value: function clear() {
  1341. var _this2 = this;
  1342. var imgs = this.getImgs();
  1343. imgs.forEach(function (el) {
  1344. return _this2.lazy.remove(el);
  1345. });
  1346. this.vnode = null;
  1347. this.binding = null;
  1348. this.lazy = null;
  1349. }
  1350. }]);
  1351. return LazyContainer;
  1352. }();
  1353. LazyContainer.install = function (Vue) {
  1354. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1355. var LazyClass = Lazy(Vue);
  1356. var lazy = new LazyClass(options);
  1357. var lazyContainer = new LazyContainer({ lazy: lazy });
  1358. var isVue2 = Vue.version.split('.')[0] === '2';
  1359. if (isVue2) {
  1360. Vue.directive('lazy-container', {
  1361. bind: lazyContainer.bind.bind(lazyContainer),
  1362. componentUpdated: lazyContainer.update.bind(lazyContainer),
  1363. unbind: lazyContainer.unbind.bind(lazyContainer)
  1364. });
  1365. } else {
  1366. Vue.directive('lazy-container', {
  1367. update: function update(newValue, oldValue) {
  1368. lazyContainer.update(this.el, {
  1369. modifiers: this.modifiers || {},
  1370. arg: this.arg,
  1371. value: newValue,
  1372. oldValue: oldValue
  1373. }, {
  1374. context: this.vm
  1375. });
  1376. },
  1377. unbind: function unbind() {
  1378. lazyContainer.unbind(this.el);
  1379. }
  1380. });
  1381. }
  1382. };
  1383. var LazyImage = function LazyImage(lazyManager) {
  1384. return {
  1385. props: {
  1386. src: [String, Object],
  1387. tag: {
  1388. type: String,
  1389. default: 'img'
  1390. }
  1391. },
  1392. render: function render(h) {
  1393. return h(this.tag, {
  1394. attrs: {
  1395. src: this.renderSrc
  1396. }
  1397. }, this.$slots.default);
  1398. },
  1399. data: function data() {
  1400. return {
  1401. el: null,
  1402. options: {
  1403. src: '',
  1404. error: '',
  1405. loading: '',
  1406. attempt: lazyManager.options.attempt
  1407. },
  1408. state: {
  1409. loaded: false,
  1410. error: false,
  1411. attempt: 0
  1412. },
  1413. rect: {},
  1414. renderSrc: ''
  1415. };
  1416. },
  1417. watch: {
  1418. src: function src() {
  1419. this.init();
  1420. lazyManager.addLazyBox(this);
  1421. lazyManager.lazyLoadHandler();
  1422. }
  1423. },
  1424. created: function created() {
  1425. this.init();
  1426. this.renderSrc = this.options.loading;
  1427. },
  1428. mounted: function mounted() {
  1429. this.el = this.$el;
  1430. lazyManager.addLazyBox(this);
  1431. lazyManager.lazyLoadHandler();
  1432. },
  1433. beforeDestroy: function beforeDestroy() {
  1434. lazyManager.removeComponent(this);
  1435. },
  1436. methods: {
  1437. init: function init() {
  1438. var _lazyManager$_valueFo = lazyManager._valueFormatter(this.src),
  1439. src = _lazyManager$_valueFo.src,
  1440. loading = _lazyManager$_valueFo.loading,
  1441. error = _lazyManager$_valueFo.error;
  1442. this.state.loaded = false;
  1443. this.options.src = src;
  1444. this.options.error = error;
  1445. this.options.loading = loading;
  1446. this.renderSrc = this.options.loading;
  1447. },
  1448. getRect: function getRect() {
  1449. this.rect = this.$el.getBoundingClientRect();
  1450. },
  1451. checkInView: function checkInView() {
  1452. this.getRect();
  1453. return inBrowser && this.rect.top < window.innerHeight * lazyManager.options.preLoad && this.rect.bottom > 0 && this.rect.left < window.innerWidth * lazyManager.options.preLoad && this.rect.right > 0;
  1454. },
  1455. load: function load() {
  1456. var _this = this;
  1457. var onFinish = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : noop;
  1458. if (this.state.attempt > this.options.attempt - 1 && this.state.error) {
  1459. if (!lazyManager.options.silent) console.log('VueLazyload log: ' + this.options.src + ' tried too more than ' + this.options.attempt + ' times');
  1460. onFinish();
  1461. return;
  1462. }
  1463. var src = this.options.src;
  1464. loadImageAsync({ src: src }, function (_ref) {
  1465. var src = _ref.src;
  1466. _this.renderSrc = src;
  1467. _this.state.loaded = true;
  1468. }, function (e) {
  1469. _this.state.attempt++;
  1470. _this.renderSrc = _this.options.error;
  1471. _this.state.error = true;
  1472. });
  1473. }
  1474. }
  1475. };
  1476. };
  1477. LazyImage.install = function (Vue) {
  1478. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1479. var LazyClass = Lazy(Vue);
  1480. var lazy = new LazyClass(options);
  1481. Vue.component('lazy-image', LazyImage(lazy));
  1482. };
  1483. var index = {
  1484. /*
  1485. * install function
  1486. * @param {Vue} Vue
  1487. * @param {object} options lazyload options
  1488. */
  1489. install: function install(Vue) {
  1490. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1491. var LazyClass = Lazy(Vue);
  1492. var lazy = new LazyClass(options);
  1493. var lazyContainer = new LazyContainerMananger({ lazy: lazy });
  1494. var isVue2 = Vue.version.split('.')[0] === '2';
  1495. Vue.prototype.$Lazyload = lazy;
  1496. if (options.lazyComponent) {
  1497. Vue.component('lazy-component', LazyComponent(lazy));
  1498. }
  1499. if (options.lazyImage) {
  1500. Vue.component('lazy-image', LazyImage(lazy));
  1501. }
  1502. if (isVue2) {
  1503. Vue.directive('lazy', {
  1504. bind: lazy.add.bind(lazy),
  1505. update: lazy.update.bind(lazy),
  1506. componentUpdated: lazy.lazyLoadHandler.bind(lazy),
  1507. unbind: lazy.remove.bind(lazy)
  1508. });
  1509. Vue.directive('lazy-container', {
  1510. bind: lazyContainer.bind.bind(lazyContainer),
  1511. componentUpdated: lazyContainer.update.bind(lazyContainer),
  1512. unbind: lazyContainer.unbind.bind(lazyContainer)
  1513. });
  1514. } else {
  1515. Vue.directive('lazy', {
  1516. bind: lazy.lazyLoadHandler.bind(lazy),
  1517. update: function update(newValue, oldValue) {
  1518. assignDeep(this.vm.$refs, this.vm.$els);
  1519. lazy.add(this.el, {
  1520. modifiers: this.modifiers || {},
  1521. arg: this.arg,
  1522. value: newValue,
  1523. oldValue: oldValue
  1524. }, {
  1525. context: this.vm
  1526. });
  1527. },
  1528. unbind: function unbind() {
  1529. lazy.remove(this.el);
  1530. }
  1531. });
  1532. Vue.directive('lazy-container', {
  1533. update: function update(newValue, oldValue) {
  1534. lazyContainer.update(this.el, {
  1535. modifiers: this.modifiers || {},
  1536. arg: this.arg,
  1537. value: newValue,
  1538. oldValue: oldValue
  1539. }, {
  1540. context: this.vm
  1541. });
  1542. },
  1543. unbind: function unbind() {
  1544. lazyContainer.unbind(this.el);
  1545. }
  1546. });
  1547. }
  1548. }
  1549. };
  1550. export { Lazy, LazyComponent, LazyContainerMananger as LazyContainer, LazyImage, index as default };