vue-lazyload.esm.js 44 KB

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