From c0397e1e926f2e388faadad437b97e0bbf047fb5 Mon Sep 17 00:00:00 2001 From: yugasun Date: Mon, 11 Dec 2017 14:25:31 +0800 Subject: [PATCH 1/4] Fix: silent config not work bug --- src/lazy.js | 563 ++++++++++++++++++++++++------------------------ vue-lazyload.js | 2 +- 2 files changed, 282 insertions(+), 283 deletions(-) diff --git a/src/lazy.js b/src/lazy.js index bc88c5a..d015e7d 100644 --- a/src/lazy.js +++ b/src/lazy.js @@ -1,8 +1,8 @@ -import { +import { inBrowser, - remove, - some, - find, + remove, + some, + find, _, throttle, supportWebp, @@ -20,259 +20,258 @@ import ReactiveListener from './listener' const DEFAULT_URL = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' const DEFAULT_EVENTS = ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend', 'touchmove'] const DEFAULT_OBSERVER_OPTIONS = { - rootMargin: '0px', - threshold: 0 + rootMargin: '0px', + threshold: 0 } export default function (Vue) { - return class Lazy { - constructor ({ preLoad, error, throttleWait, preLoadTop, dispatchEvent, loading, attempt, silent, scale, listenEvents, hasbind, filter, adapter, observer, observerOptions }) { - this.version = '__VUE_LAZYLOAD_VERSION__' - this.mode = modeType.event - this.ListenerQueue = [] - this.TargetIndex = 0 - this.TargetQueue = [] - this.options = { - silent: silent || true, - dispatchEvent: !!dispatchEvent, - throttleWait: throttleWait || 200, - preLoad: preLoad || 1.3, - preLoadTop: preLoadTop || 0, - error: error || DEFAULT_URL, - loading: loading || DEFAULT_URL, - attempt: attempt || 3, - scale: scale || getDPR(scale), - ListenEvents: listenEvents || DEFAULT_EVENTS, - hasbind: false, - supportWebp: supportWebp(), - filter: filter || {}, - adapter: adapter || {}, - observer: !!observer, - observerOptions: observerOptions || DEFAULT_OBSERVER_OPTIONS - } - this._initEvent() + return class Lazy { + constructor ({ preLoad, error, throttleWait, preLoadTop, dispatchEvent, loading, attempt, silent = true, scale, listenEvents, hasbind, filter, adapter, observer, observerOptions }) { + this.version = '__VUE_LAZYLOAD_VERSION__' + this.mode = modeType.event + this.ListenerQueue = [] + this.TargetIndex = 0 + this.TargetQueue = [] + this.options = { + silent: silent, + dispatchEvent: !!dispatchEvent, + throttleWait: throttleWait || 200, + preLoad: preLoad || 1.3, + preLoadTop: preLoadTop || 0, + error: error || DEFAULT_URL, + loading: loading || DEFAULT_URL, + attempt: attempt || 3, + scale: scale || getDPR(scale), + ListenEvents: listenEvents || DEFAULT_EVENTS, + hasbind: false, + supportWebp: supportWebp(), + filter: filter || {}, + adapter: adapter || {}, + observer: !!observer, + observerOptions: observerOptions || DEFAULT_OBSERVER_OPTIONS + } + this._initEvent() - this.lazyLoadHandler = throttle(this._lazyLoadHandler.bind(this), this.options.throttleWait) + this.lazyLoadHandler = throttle(this._lazyLoadHandler.bind(this), this.options.throttleWait) - this.setMode(this.options.observer ? modeType.observer : modeType.event) - } + this.setMode(this.options.observer ? modeType.observer : modeType.event) + } /** * update config * @param {Object} config params * @return */ - config (options = {}) { - assign(this.options, options) - } + config (options = {}) { + assign(this.options, options) + } /** * output listener's load performance - * @return {Array} + * @return {Array} */ - performance () { - let list = [] + performance () { + let list = [] - this.ListenerQueue.map(item => { - list.push(item.performance()) - }) - - return list - } + this.ListenerQueue.map(item => { + list.push(item.performance()) + }) + return list + } /** * add lazy component to queue * @param {Vue} vm lazy component instance * @return */ - addLazyBox (vm) { - this.ListenerQueue.push(vm) - if (inBrowser) { - this._addListenerTarget(window) - this._observer && this._observer.observe(vm.el) - if (vm.$el && vm.$el.parentNode) { - this._addListenerTarget(vm.$el.parentNode) - } + addLazyBox (vm) { + this.ListenerQueue.push(vm) + if (inBrowser) { + this._addListenerTarget(window) + this._observer && this._observer.observe(vm.el) + if (vm.$el && vm.$el.parentNode) { + this._addListenerTarget(vm.$el.parentNode) } } + } /** * add image listener to queue - * @param {DOM} el + * @param {DOM} el * @param {object} binding vue directive binding * @param {vnode} vnode vue directive vnode * @return */ - add (el, binding, vnode) { - if (some(this.ListenerQueue, item => item.el === el)) { - this.update(el, binding) - return Vue.nextTick(this.lazyLoadHandler) - } + add (el, binding, vnode) { + if (some(this.ListenerQueue, item => item.el === el)) { + this.update(el, binding) + return Vue.nextTick(this.lazyLoadHandler) + } - let { src, loading, error } = this._valueFormatter(binding.value) + let { src, loading, error } = this._valueFormatter(binding.value) - Vue.nextTick(() => { - src = getBestSelectionFromSrcset(el, this.options.scale) || src - this._observer && this._observer.observe(el) + Vue.nextTick(() => { + src = getBestSelectionFromSrcset(el, this.options.scale) || src + this._observer && this._observer.observe(el) - const container = Object.keys(binding.modifiers)[0] - let $parent + const container = Object.keys(binding.modifiers)[0] + let $parent - if (container) { - $parent = vnode.context.$refs[container] + if (container) { + $parent = vnode.context.$refs[container] // if there is container passed in, try ref first, then fallback to getElementById to support the original usage - $parent = $parent ? $parent.$el || $parent : document.getElementById(container) - } + $parent = $parent ? $parent.$el || $parent : document.getElementById(container) + } - if (!$parent) { - $parent = scrollParent(el) - } + if (!$parent) { + $parent = scrollParent(el) + } - const newListener = new ReactiveListener({ - bindType: binding.arg, - $parent, - el, - loading, - error, - src, - elRenderer: this._elRenderer.bind(this), - options: this.options - }) + const newListener = new ReactiveListener({ + bindType: binding.arg, + $parent, + el, + loading, + error, + src, + elRenderer: this._elRenderer.bind(this), + options: this.options + }) - this.ListenerQueue.push(newListener) + this.ListenerQueue.push(newListener) - if (inBrowser) { - this._addListenerTarget(window) - this._addListenerTarget($parent) - } + if (inBrowser) { + this._addListenerTarget(window) + this._addListenerTarget($parent) + } - this.lazyLoadHandler() - Vue.nextTick(() => this.lazyLoadHandler()) - }) - } + this.lazyLoadHandler() + Vue.nextTick(() => this.lazyLoadHandler()) + }) + } /** * update image src - * @param {DOM} el + * @param {DOM} el * @param {object} vue directive binding * @return */ - update (el, binding) { - let { src, loading, error } = this._valueFormatter(binding.value) - src = getBestSelectionFromSrcset(el, this.options.scale) || src - - const exist = find(this.ListenerQueue, item => item.el === el) - - exist && exist.update({ - src, - loading, - error - }) - this._observer && this._observer.observe(el) - this.lazyLoadHandler() - Vue.nextTick(() => this.lazyLoadHandler()) - } + update (el, binding) { + let { src, loading, error } = this._valueFormatter(binding.value) + src = getBestSelectionFromSrcset(el, this.options.scale) || src + + const exist = find(this.ListenerQueue, item => item.el === el) + + exist && exist.update({ + src, + loading, + error + }) + this._observer && this._observer.observe(el) + this.lazyLoadHandler() + Vue.nextTick(() => this.lazyLoadHandler()) + } /** * remove listener form list - * @param {DOM} el + * @param {DOM} el * @return */ - remove (el) { - if (!el) return - this._observer && this._observer.unobserve(el) - const existItem = find(this.ListenerQueue, item => item.el === el) - if (existItem) { - this._removeListenerTarget(existItem.$parent) - this._removeListenerTarget(window) - remove(this.ListenerQueue, existItem) && existItem.destroy() - } + remove (el) { + if (!el) return + this._observer && this._observer.unobserve(el) + const existItem = find(this.ListenerQueue, item => item.el === el) + if (existItem) { + this._removeListenerTarget(existItem.$parent) + this._removeListenerTarget(window) + remove(this.ListenerQueue, existItem) && existItem.destroy() } + } /** * remove lazy components form list - * @param {Vue} vm Vue instance + * @param {Vue} vm Vue instance * @return */ - removeComponent (vm) { - if (!vm) return - remove(this.ListenerQueue, vm) - this._observer && this._observer.unobserve(vm.el) - if (vm.$parent && vm.$el.parentNode) { - this._removeListenerTarget(vm.$el.parentNode) - } - this._removeListenerTarget(window) + removeComponent (vm) { + if (!vm) return + remove(this.ListenerQueue, vm) + this._observer && this._observer.unobserve(vm.el) + if (vm.$parent && vm.$el.parentNode) { + this._removeListenerTarget(vm.$el.parentNode) } + this._removeListenerTarget(window) + } - setMode (mode) { - if (!hasIntersectionObserver && mode === modeType.observer) { - mode = modeType.event - } + setMode (mode) { + if (!hasIntersectionObserver && mode === modeType.observer) { + mode = modeType.event + } - this.mode = mode // event or observer - - if (mode === modeType.event) { - if (this._observer) { - this.ListenerQueue.forEach(listener => { - this._observer.unobserve(listener.el) - }) - this._observer = null - } + this.mode = mode // event or observer - this.TargetQueue.forEach(target => { - this._initListen(target.el, true) - }) - } else { - this.TargetQueue.forEach(target => { - this._initListen(target.el, false) + if (mode === modeType.event) { + if (this._observer) { + this.ListenerQueue.forEach(listener => { + this._observer.unobserve(listener.el) }) - this._initIntersectionObserver() + this._observer = null } + + this.TargetQueue.forEach(target => { + this._initListen(target.el, true) + }) + } else { + this.TargetQueue.forEach(target => { + this._initListen(target.el, false) + }) + this._initIntersectionObserver() } - - /**** Private functions ****/ + } + + /** ** Private functions ****/ /** * add listener target - * @param {DOM} el listener target + * @param {DOM} el listener target * @return */ - _addListenerTarget (el) { - if (!el) return - let target = find(this.TargetQueue, target => target.el === el) - if (!target) { - target = { - el: el, - id: ++this.TargetIndex, - childrenCount: 1, - listened: true - } - this.mode === modeType.event && this._initListen(target.el, true) - this.TargetQueue.push(target) - } else { - target.childrenCount++ + _addListenerTarget (el) { + if (!el) return + let target = find(this.TargetQueue, target => target.el === el) + if (!target) { + target = { + el: el, + id: ++this.TargetIndex, + childrenCount: 1, + listened: true } - return this.TargetIndex + this.mode === modeType.event && this._initListen(target.el, true) + this.TargetQueue.push(target) + } else { + target.childrenCount++ } + return this.TargetIndex + } /** * remove listener target or reduce target childrenCount * @param {DOM} el or window * @return */ - _removeListenerTarget (el) { - this.TargetQueue.forEach((target, index) => { - if (target.el === el) { - target.childrenCount-- - if (!target.childrenCount) { - this._initListen(target.el, false) - this.TargetQueue.splice(index, 1) - target = null - } + _removeListenerTarget (el) { + this.TargetQueue.forEach((target, index) => { + if (target.el === el) { + target.childrenCount-- + if (!target.childrenCount) { + this._initListen(target.el, false) + this.TargetQueue.splice(index, 1) + target = null } - }) - } + } + }) + } /** * add or remove eventlistener @@ -280,156 +279,156 @@ export default function (Vue) { * @param {boolean} start flag * @return */ - _initListen (el, start) { - this.options.ListenEvents.forEach((evt) => _[start ? 'on' : 'off'](el, evt, this.lazyLoadHandler)) - } + _initListen (el, start) { + this.options.ListenEvents.forEach((evt) => _[start ? 'on' : 'off'](el, evt, this.lazyLoadHandler)) + } - _initEvent () { - this.Event = { - listeners: { - loading: [], - loaded: [], - error: [] - } + _initEvent () { + this.Event = { + listeners: { + loading: [], + loaded: [], + error: [] } + } - this.$on = (event, func) => { - this.Event.listeners[event].push(func) - } + this.$on = (event, func) => { + this.Event.listeners[event].push(func) + } - this.$once = (event, func) => { - const vm = this - function on () { - vm.$off(event, on) - func.apply(vm, arguments) - } - this.$on(event, on) + this.$once = (event, func) => { + const vm = this + function on () { + vm.$off(event, on) + func.apply(vm, arguments) } + this.$on(event, on) + } - this.$off = (event, func) => { - if (!func) { - this.Event.listeners[event] = [] - return - } - remove(this.Event.listeners[event], func) + this.$off = (event, func) => { + if (!func) { + this.Event.listeners[event] = [] + return } + remove(this.Event.listeners[event], func) + } - this.$emit = (event, context, inCache) => { - this.Event.listeners[event].forEach(func => func(context, inCache)) - } + this.$emit = (event, context, inCache) => { + this.Event.listeners[event].forEach(func => func(context, inCache)) } + } /** * find nodes which in viewport and trigger load * @return */ - _lazyLoadHandler () { - let catIn = false - this.ListenerQueue.forEach(listener => { - if (listener.state.loaded) return - catIn = listener.checkInView() - catIn && listener.load() - }) - } + _lazyLoadHandler () { + console.log(this) + let catIn = false + this.ListenerQueue.forEach(listener => { + if (listener.state.loaded) return + catIn = listener.checkInView() + catIn && listener.load() + }) + } /** * init IntersectionObserver * set mode to observer * @return */ - _initIntersectionObserver () { - if (!hasIntersectionObserver) return - this._observer = new IntersectionObserver(this._observerHandler.bind(this), this.options.observerOptions) - if (this.ListenerQueue.length) { - this.ListenerQueue.forEach(listener => { - this._observer.observe(listener.el) - }) - } + _initIntersectionObserver () { + if (!hasIntersectionObserver) return + this._observer = new IntersectionObserver(this._observerHandler.bind(this), this.options.observerOptions) + if (this.ListenerQueue.length) { + this.ListenerQueue.forEach(listener => { + this._observer.observe(listener.el) + }) } + } /** * init IntersectionObserver * @return */ - _observerHandler (entries, observer) { - entries.forEach(entry => { - if (entry.isIntersecting) { - this.ListenerQueue.forEach(listener => { - if (listener.el === entry.target) { - if (listener.state.loaded) return this._observer.unobserve(listener.el) - listener.load() - } - - }) - } - }) - } + _observerHandler (entries, observer) { + entries.forEach(entry => { + if (entry.isIntersecting) { + this.ListenerQueue.forEach(listener => { + if (listener.el === entry.target) { + if (listener.state.loaded) return this._observer.unobserve(listener.el) + listener.load() + } + }) + } + }) + } /** * set element attribute with image'url and state * @param {object} lazyload listener object * @param {string} state will be rendered - * @param {bool} inCache is rendered from cache + * @param {bool} inCache is rendered from cache * @return */ - _elRenderer (listener, state, cache) { - if (!listener.el) return - const { el, bindType } = listener - - let src - switch (state) { - case 'loading': - src = listener.loading - break - case 'error': - src = listener.error - break - default: - src = listener.src - break - } + _elRenderer (listener, state, cache) { + if (!listener.el) return + const { el, bindType } = listener + + let src + switch (state) { + case 'loading': + src = listener.loading + break + case 'error': + src = listener.error + break + default: + src = listener.src + break + } - if (bindType) { - el.style[bindType] = 'url(' + src + ')' - } else if (el.getAttribute('src') !== src) { - el.setAttribute('src', src) - } + if (bindType) { + el.style[bindType] = 'url(' + src + ')' + } else if (el.getAttribute('src') !== src) { + el.setAttribute('src', src) + } - el.setAttribute('lazy', state) + el.setAttribute('lazy', state) - this.$emit(state, listener, cache) - this.options.adapter[state] && this.options.adapter[state](listener, this.options) + this.$emit(state, listener, cache) + this.options.adapter[state] && this.options.adapter[state](listener, this.options) - if (this.options.dispatchEvent) { - const event = new CustomEvent(state, { - detail: listener - }) - el.dispatchEvent(event) - } + if (this.options.dispatchEvent) { + const event = new CustomEvent(state, { + detail: listener + }) + el.dispatchEvent(event) } + } /** - * generate loading loaded error image url + * generate loading loaded error image url * @param {string} image's src * @return {object} image's loading, loaded, error url */ - _valueFormatter (value) { - let src = value - let loading = this.options.loading - let error = this.options.error + _valueFormatter (value) { + let src = value + let loading = this.options.loading + let error = this.options.error // value is object - if (isObject(value)) { - if (!value.src && !this.options.silent) console.error('Vue Lazyload warning: miss src with ' + value) - src = value.src - loading = value.loading || this.options.loading - error = value.error || this.options.error - } - return { - src, - loading, - error - } + if (isObject(value)) { + if (!value.src && !this.options.silent) console.error('Vue Lazyload warning: miss src with ' + value) + src = value.src + loading = value.loading || this.options.loading + error = value.error || this.options.error } + return { + src, + loading, + error + } + } } } diff --git a/vue-lazyload.js b/vue-lazyload.js index e048be2..4cf7efb 100644 --- a/vue-lazyload.js +++ b/vue-lazyload.js @@ -3,4 +3,4 @@ * (c) 2017 Awe * Released under the MIT License. */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.VueLazyload=t()}(this,function(){"use strict";function e(e,t){if(e.length){var n=e.indexOf(t);return n>-1?e.splice(n,1):void 0}}function t(e,t){if(!e||!t)return e||{};if(e instanceof Object)for(var n in t)e[n]=t[n];return e}function n(e,t){for(var n=!1,r=0,i=e.length;rt[0])return 1;if(e[0]===t[0]){if(-1!==t[1].indexOf(".webp",t[1].length-5))return 1;if(-1!==e[1].indexOf(".webp",e[1].length-5))return-1}return 0});for(var l="",d=void 0,c=r.length,h=0;h=o){l=d[1];break}return l}}function i(e,t){for(var n=void 0,r=0,i=e.length;r=t?a():n=setTimeout(a,t)}}}function a(e){return null!==e&&"object"===(void 0===e?"undefined":c(e))}function u(e){if(!(e instanceof Object))return[];if(Object.keys)return Object.keys(e);var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n);return t}function l(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function d(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},h="undefined"!=typeof window,f=h&&"IntersectionObserver"in window,v={event:"event",observer:"observer"},p=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;return h&&window.devicePixelRatio||e},g=function(){if(h){var e=!1;try{var t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",null,t)}catch(e){}return e}}(),y={on:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];g?e.addEventListener(t,n,{capture:r,passive:!0}):e.addEventListener(t,n,r)},off:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];e.removeEventListener(t,n,r)}},b=function(e,t,n){var r=new Image;r.src=e.src,r.onload=function(){t({naturalHeight:r.naturalHeight,naturalWidth:r.naturalWidth,src:r.src})},r.onerror=function(e){n(e)}},m=function(e,t){return"undefined"!=typeof getComputedStyle?getComputedStyle(e,null).getPropertyValue(t):e.style[t]},L=function(e){return m(e,"overflow")+m(e,"overflow-y")+m(e,"overflow-x")},w=function(e){if(h){if(!(e instanceof HTMLElement))return window;for(var t=e;t&&t!==document.body&&t!==document.documentElement&&t.parentNode;){if(/(scroll|auto)/.test(L(t)))return t;t=t.parentNode}return window}},_=function(){function e(e,t){for(var n=0;nthis.options.preLoadTop&&this.rect.left0}},{key:"filter",value:function(){var e=this;u(this.options.filter).map(function(t){e.options.filter[t](e,e.options)})}},{key:"renderLoading",value:function(e){var t=this;b({src:this.loading},function(n){t.render("loading",!1),e()},function(n){e(),t.options.silent||console.warn("VueLazyload log: load failed with loading image("+t.loading+")")})}},{key:"load",value:function(){var e=this;return this.attempt>this.options.attempt-1&&this.state.error?void(this.options.silent||console.log("VueLazyload log: "+this.src+" tried too more than "+this.options.attempt+" times")):this.state.loaded||k[this.src]?this.render("loaded",!0):void this.renderLoading(function(){e.attempt++,e.record("loadStart"),b({src:e.src},function(t){e.naturalHeight=t.naturalHeight,e.naturalWidth=t.naturalWidth,e.state.loaded=!0,e.state.error=!1,e.record("loadEnd"),e.render("loaded",!1),k[e.src]=1},function(t){e.state.error=!0,e.state.loaded=!1,e.render("error",!1)})})}},{key:"render",value:function(e,t){this.elRenderer(this,e,t)}},{key:"performance",value:function(){var e="loading",t=0;return this.state.loaded&&(e="loaded",t=(this.performanceData.loadEnd-this.performanceData.loadStart)/1e3),this.state.error&&(e="error"),{src:this.src,state:e,time:t}}},{key:"destroy",value:function(){this.el=null,this.src=null,this.error=null,this.loading=null,this.bindType=null,this.attempt=0}}]),e}(),T=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{};t(this.options,e)}},{key:"performance",value:function(){var e=[];return this.ListenerQueue.map(function(t){e.push(t.performance())}),e}},{key:"addLazyBox",value:function(e){this.ListenerQueue.push(e),h&&(this._addListenerTarget(window),this._observer&&this._observer.observe(e.el),e.$el&&e.$el.parentNode&&this._addListenerTarget(e.$el.parentNode))}},{key:"add",value:function(e,t,i){var o=this;if(n(this.ListenerQueue,function(t){return t.el===e}))return this.update(e,t),u.nextTick(this.lazyLoadHandler);var s=this._valueFormatter(t.value),a=s.src,l=s.loading,d=s.error;u.nextTick(function(){a=r(e,o.options.scale)||a,o._observer&&o._observer.observe(e);var n=Object.keys(t.modifiers)[0],s=void 0;n&&(s=i.context.$refs[n],s=s?s.$el||s:document.getElementById(n)),s||(s=w(e));var c=new E({bindType:t.arg,$parent:s,el:e,loading:l,error:d,src:a,elRenderer:o._elRenderer.bind(o),options:o.options});o.ListenerQueue.push(c),h&&(o._addListenerTarget(window),o._addListenerTarget(s)),o.lazyLoadHandler(),u.nextTick(function(){return o.lazyLoadHandler()})})}},{key:"update",value:function(e,t){var n=this,o=this._valueFormatter(t.value),s=o.src,a=o.loading,l=o.error;s=r(e,this.options.scale)||s;var d=i(this.ListenerQueue,function(t){return t.el===e});d&&d.update({src:s,loading:a,error:l}),this._observer&&this._observer.observe(e),this.lazyLoadHandler(),u.nextTick(function(){return n.lazyLoadHandler()})}},{key:"remove",value:function(t){if(t){this._observer&&this._observer.unobserve(t);var n=i(this.ListenerQueue,function(e){return e.el===t});n&&(this._removeListenerTarget(n.$parent),this._removeListenerTarget(window),e(this.ListenerQueue,n)&&n.destroy())}}},{key:"removeComponent",value:function(t){t&&(e(this.ListenerQueue,t),this._observer&&this._observer.unobserve(t.el),t.$parent&&t.$el.parentNode&&this._removeListenerTarget(t.$el.parentNode),this._removeListenerTarget(window))}},{key:"setMode",value:function(e){var t=this;f||e!==v.observer||(e=v.event),this.mode=e,e===v.event?(this._observer&&(this.ListenerQueue.forEach(function(e){t._observer.unobserve(e.el)}),this._observer=null),this.TargetQueue.forEach(function(e){t._initListen(e.el,!0)})):(this.TargetQueue.forEach(function(e){t._initListen(e.el,!1)}),this._initIntersectionObserver())}},{key:"_addListenerTarget",value:function(e){if(e){var t=i(this.TargetQueue,function(t){return t.el===e});return t?t.childrenCount++:(t={el:e,id:++this.TargetIndex,childrenCount:1,listened:!0},this.mode===v.event&&this._initListen(t.el,!0),this.TargetQueue.push(t)),this.TargetIndex}}},{key:"_removeListenerTarget",value:function(e){var t=this;this.TargetQueue.forEach(function(n,r){n.el===e&&(--n.childrenCount||(t._initListen(n.el,!1),t.TargetQueue.splice(r,1),n=null))})}},{key:"_initListen",value:function(e,t){var n=this;this.options.ListenEvents.forEach(function(r){return y[t?"on":"off"](e,r,n.lazyLoadHandler)})}},{key:"_initEvent",value:function(){var t=this;this.Event={listeners:{loading:[],loaded:[],error:[]}},this.$on=function(e,n){t.Event.listeners[e].push(n)},this.$once=function(e,n){function r(){i.$off(e,r),n.apply(i,arguments)}var i=t;t.$on(e,r)},this.$off=function(n,r){if(!r)return void(t.Event.listeners[n]=[]);e(t.Event.listeners[n],r)},this.$emit=function(e,n,r){t.Event.listeners[e].forEach(function(e){return e(n,r)})}}},{key:"_lazyLoadHandler",value:function(){var e=!1;this.ListenerQueue.forEach(function(t){t.state.loaded||(e=t.checkInView())&&t.load()})}},{key:"_initIntersectionObserver",value:function(){var e=this;f&&(this._observer=new IntersectionObserver(this._observerHandler.bind(this),this.options.observerOptions),this.ListenerQueue.length&&this.ListenerQueue.forEach(function(t){e._observer.observe(t.el)}))}},{key:"_observerHandler",value:function(e,t){var n=this;e.forEach(function(e){e.isIntersecting&&n.ListenerQueue.forEach(function(t){if(t.el===e.target){if(t.state.loaded)return n._observer.unobserve(t.el);t.load()}})})}},{key:"_elRenderer",value:function(e,t,n){if(e.el){var r=e.el,i=e.bindType,o=void 0;switch(t){case"loading":o=e.loading;break;case"error":o=e.error;break;default:o=e.src}if(i?r.style[i]="url("+o+")":r.getAttribute("src")!==o&&r.setAttribute("src",o),r.setAttribute("lazy",t),this.$emit(t,e,n),this.options.adapter[t]&&this.options.adapter[t](e,this.options),this.options.dispatchEvent){var s=new CustomEvent(t,{detail:e});r.dispatchEvent(s)}}}},{key:"_valueFormatter",value:function(e){var t=e,n=this.options.loading,r=this.options.error;return a(e)&&(e.src||this.options.silent||console.error("Vue Lazyload warning: miss src with "+e),t=e.src,n=e.loading||this.options.loading,r=e.error||this.options.error),{src:t,loading:n,error:r}}}]),l}()},O=function(e){return{props:{tag:{type:String,default:"div"}},render:function(e){return!1===this.show?e(this.tag):e(this.tag,null,this.$slots.default)},data:function(){return{el:null,state:{loaded:!1},rect:{},show:!1}},mounted:function(){this.el=this.$el,e.addLazyBox(this),e.lazyLoadHandler()},beforeDestroy:function(){e.removeComponent(this)},methods:{getRect:function(){this.rect=this.$el.getBoundingClientRect()},checkInView:function(){return this.getRect(),h&&this.rect.top0&&this.rect.left0},load:function(){this.show=!0,this.state.loaded=!0,this.$emit("show",this)}}}};return{install:function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=H(e),i=new r(n),o="2"===e.version.split(".")[0];e.prototype.$Lazyload=i,n.lazyComponent&&e.component("lazy-component",O(i)),o?e.directive("lazy",{bind:i.add.bind(i),update:i.update.bind(i),componentUpdated:i.lazyLoadHandler.bind(i),unbind:i.remove.bind(i)}):e.directive("lazy",{bind:i.lazyLoadHandler.bind(i),update:function(e,n){t(this.vm.$refs,this.vm.$els),i.add(this.el,{modifiers:this.modifiers||{},arg:this.arg,value:e,oldValue:n},{context:this.vm})},unbind:function(){i.remove(this.el)}})}}}); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.VueLazyload=t()}(this,function(){"use strict";function e(e,t){if(e.length){var n=e.indexOf(t);return n>-1?e.splice(n,1):void 0}}function t(e,t){if(!e||!t)return e||{};if(e instanceof Object)for(var n in t)e[n]=t[n];return e}function n(e,t){for(var n=!1,r=0,i=e.length;rt[0])return 1;if(e[0]===t[0]){if(-1!==t[1].indexOf(".webp",t[1].length-5))return 1;if(-1!==e[1].indexOf(".webp",e[1].length-5))return-1}return 0});for(var l="",d=void 0,h=r.length,c=0;c=o){l=d[1];break}return l}}function i(e,t){for(var n=void 0,r=0,i=e.length;r=t?a():n=setTimeout(a,t)}}}function a(e){return null!==e&&"object"===(void 0===e?"undefined":h(e))}function u(e){if(!(e instanceof Object))return[];if(Object.keys)return Object.keys(e);var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n);return t}function l(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function d(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},c="undefined"!=typeof window,f=c&&"IntersectionObserver"in window,v={event:"event",observer:"observer"},p=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;return c&&window.devicePixelRatio||e},g=function(){if(c){var e=!1;try{var t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",null,t)}catch(e){}return e}}(),y={on:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];g?e.addEventListener(t,n,{capture:r,passive:!0}):e.addEventListener(t,n,r)},off:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];e.removeEventListener(t,n,r)}},b=function(e,t,n){var r=new Image;r.src=e.src,r.onload=function(){t({naturalHeight:r.naturalHeight,naturalWidth:r.naturalWidth,src:r.src})},r.onerror=function(e){n(e)}},m=function(e,t){return"undefined"!=typeof getComputedStyle?getComputedStyle(e,null).getPropertyValue(t):e.style[t]},L=function(e){return m(e,"overflow")+m(e,"overflow-y")+m(e,"overflow-x")},w=function(e){if(c){if(!(e instanceof HTMLElement))return window;for(var t=e;t&&t!==document.body&&t!==document.documentElement&&t.parentNode;){if(/(scroll|auto)/.test(L(t)))return t;t=t.parentNode}return window}},_=function(){function e(e,t){for(var n=0;nthis.options.preLoadTop&&this.rect.left0}},{key:"filter",value:function(){var e=this;u(this.options.filter).map(function(t){e.options.filter[t](e,e.options)})}},{key:"renderLoading",value:function(e){var t=this;b({src:this.loading},function(n){t.render("loading",!1),e()},function(n){e(),t.options.silent||console.warn("VueLazyload log: load failed with loading image("+t.loading+")")})}},{key:"load",value:function(){var e=this;return this.attempt>this.options.attempt-1&&this.state.error?void(this.options.silent||console.log("VueLazyload log: "+this.src+" tried too more than "+this.options.attempt+" times")):this.state.loaded||k[this.src]?(this.state.loaded=!0,this.render("loaded",!0)):void this.renderLoading(function(){e.attempt++,e.record("loadStart"),b({src:e.src},function(t){e.naturalHeight=t.naturalHeight,e.naturalWidth=t.naturalWidth,e.state.loaded=!0,e.state.error=!1,e.record("loadEnd"),e.render("loaded",!1),k[e.src]=1},function(t){e.state.error=!0,e.state.loaded=!1,e.render("error",!1)})})}},{key:"render",value:function(e,t){this.elRenderer(this,e,t)}},{key:"performance",value:function(){var e="loading",t=0;return this.state.loaded&&(e="loaded",t=(this.performanceData.loadEnd-this.performanceData.loadStart)/1e3),this.state.error&&(e="error"),{src:this.src,state:e,time:t}}},{key:"destroy",value:function(){this.el=null,this.src=null,this.error=null,this.loading=null,this.bindType=null,this.attempt=0}}]),e}(),T=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{};t(this.options,e)}},{key:"performance",value:function(){var e=[];return this.ListenerQueue.map(function(t){e.push(t.performance())}),e}},{key:"addLazyBox",value:function(e){this.ListenerQueue.push(e),c&&(this._addListenerTarget(window),this._observer&&this._observer.observe(e.el),e.$el&&e.$el.parentNode&&this._addListenerTarget(e.$el.parentNode))}},{key:"add",value:function(e,t,i){var o=this;if(n(this.ListenerQueue,function(t){return t.el===e}))return this.update(e,t),u.nextTick(this.lazyLoadHandler);var s=this._valueFormatter(t.value),a=s.src,l=s.loading,d=s.error;u.nextTick(function(){a=r(e,o.options.scale)||a,o._observer&&o._observer.observe(e);var n=Object.keys(t.modifiers)[0],s=void 0;n&&(s=i.context.$refs[n],s=s?s.$el||s:document.getElementById(n)),s||(s=w(e));var h=new E({bindType:t.arg,$parent:s,el:e,loading:l,error:d,src:a,elRenderer:o._elRenderer.bind(o),options:o.options});o.ListenerQueue.push(h),c&&(o._addListenerTarget(window),o._addListenerTarget(s)),o.lazyLoadHandler(),u.nextTick(function(){return o.lazyLoadHandler()})})}},{key:"update",value:function(e,t){var n=this,o=this._valueFormatter(t.value),s=o.src,a=o.loading,l=o.error;s=r(e,this.options.scale)||s;var d=i(this.ListenerQueue,function(t){return t.el===e});d&&d.update({src:s,loading:a,error:l}),this._observer&&this._observer.observe(e),this.lazyLoadHandler(),u.nextTick(function(){return n.lazyLoadHandler()})}},{key:"remove",value:function(t){if(t){this._observer&&this._observer.unobserve(t);var n=i(this.ListenerQueue,function(e){return e.el===t});n&&(this._removeListenerTarget(n.$parent),this._removeListenerTarget(window),e(this.ListenerQueue,n)&&n.destroy())}}},{key:"removeComponent",value:function(t){t&&(e(this.ListenerQueue,t),this._observer&&this._observer.unobserve(t.el),t.$parent&&t.$el.parentNode&&this._removeListenerTarget(t.$el.parentNode),this._removeListenerTarget(window))}},{key:"setMode",value:function(e){var t=this;f||e!==v.observer||(e=v.event),this.mode=e,e===v.event?(this._observer&&(this.ListenerQueue.forEach(function(e){t._observer.unobserve(e.el)}),this._observer=null),this.TargetQueue.forEach(function(e){t._initListen(e.el,!0)})):(this.TargetQueue.forEach(function(e){t._initListen(e.el,!1)}),this._initIntersectionObserver())}},{key:"_addListenerTarget",value:function(e){if(e){var t=i(this.TargetQueue,function(t){return t.el===e});return t?t.childrenCount++:(t={el:e,id:++this.TargetIndex,childrenCount:1,listened:!0},this.mode===v.event&&this._initListen(t.el,!0),this.TargetQueue.push(t)),this.TargetIndex}}},{key:"_removeListenerTarget",value:function(e){var t=this;this.TargetQueue.forEach(function(n,r){n.el===e&&(--n.childrenCount||(t._initListen(n.el,!1),t.TargetQueue.splice(r,1),n=null))})}},{key:"_initListen",value:function(e,t){var n=this;this.options.ListenEvents.forEach(function(r){return y[t?"on":"off"](e,r,n.lazyLoadHandler)})}},{key:"_initEvent",value:function(){var t=this;this.Event={listeners:{loading:[],loaded:[],error:[]}},this.$on=function(e,n){t.Event.listeners[e].push(n)},this.$once=function(e,n){function r(){i.$off(e,r),n.apply(i,arguments)}var i=t;t.$on(e,r)},this.$off=function(n,r){if(!r)return void(t.Event.listeners[n]=[]);e(t.Event.listeners[n],r)},this.$emit=function(e,n,r){t.Event.listeners[e].forEach(function(e){return e(n,r)})}}},{key:"_lazyLoadHandler",value:function(){console.log(this);var e=!1;this.ListenerQueue.forEach(function(t){t.state.loaded||(e=t.checkInView())&&t.load()})}},{key:"_initIntersectionObserver",value:function(){var e=this;f&&(this._observer=new IntersectionObserver(this._observerHandler.bind(this),this.options.observerOptions),this.ListenerQueue.length&&this.ListenerQueue.forEach(function(t){e._observer.observe(t.el)}))}},{key:"_observerHandler",value:function(e,t){var n=this;e.forEach(function(e){e.isIntersecting&&n.ListenerQueue.forEach(function(t){if(t.el===e.target){if(t.state.loaded)return n._observer.unobserve(t.el);t.load()}})})}},{key:"_elRenderer",value:function(e,t,n){if(e.el){var r=e.el,i=e.bindType,o=void 0;switch(t){case"loading":o=e.loading;break;case"error":o=e.error;break;default:o=e.src}if(i?r.style[i]="url("+o+")":r.getAttribute("src")!==o&&r.setAttribute("src",o),r.setAttribute("lazy",t),this.$emit(t,e,n),this.options.adapter[t]&&this.options.adapter[t](e,this.options),this.options.dispatchEvent){var s=new CustomEvent(t,{detail:e});r.dispatchEvent(s)}}}},{key:"_valueFormatter",value:function(e){var t=e,n=this.options.loading,r=this.options.error;return a(e)&&(e.src||this.options.silent||console.error("Vue Lazyload warning: miss src with "+e),t=e.src,n=e.loading||this.options.loading,r=e.error||this.options.error),{src:t,loading:n,error:r}}}]),l}()},O=function(e){return{props:{tag:{type:String,default:"div"}},render:function(e){return!1===this.show?e(this.tag):e(this.tag,null,this.$slots.default)},data:function(){return{el:null,state:{loaded:!1},rect:{},show:!1}},mounted:function(){this.el=this.$el,e.addLazyBox(this),e.lazyLoadHandler()},beforeDestroy:function(){e.removeComponent(this)},methods:{getRect:function(){this.rect=this.$el.getBoundingClientRect()},checkInView:function(){return this.getRect(),c&&this.rect.top0&&this.rect.left0},load:function(){this.show=!0,this.state.loaded=!0,this.$emit("show",this)}}}};return{install:function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=H(e),i=new r(n),o="2"===e.version.split(".")[0];e.prototype.$Lazyload=i,n.lazyComponent&&e.component("lazy-component",O(i)),o?e.directive("lazy",{bind:i.add.bind(i),update:i.update.bind(i),componentUpdated:i.lazyLoadHandler.bind(i),unbind:i.remove.bind(i)}):e.directive("lazy",{bind:i.lazyLoadHandler.bind(i),update:function(e,n){t(this.vm.$refs,this.vm.$els),i.add(this.el,{modifiers:this.modifiers||{},arg:this.arg,value:e,oldValue:n},{context:this.vm})},unbind:function(){i.remove(this.el)}})}}}); From ae70425140b4f05fb2f3e419ee5f792d9103a12f Mon Sep 17 00:00:00 2001 From: yugasun Date: Mon, 11 Dec 2017 15:06:14 +0800 Subject: [PATCH 2/4] update devDependencies and build scripts --- .babelrc | 5 ++- build.js | 100 ++++++++++++++++++++++++++---------------------- package.json | 25 ++++++------ vue-lazyload.js | 2 +- 4 files changed, 71 insertions(+), 61 deletions(-) diff --git a/.babelrc b/.babelrc index 9897749..fe1d213 100644 --- a/.babelrc +++ b/.babelrc @@ -1,5 +1,8 @@ { "presets": [ - ["es2015", { "modules": false }] + ["env", { "modules": false }] + ], + "plugins": [ + "external-helpers" ] } diff --git a/build.js b/build.js index afbeff4..874e0e1 100644 --- a/build.js +++ b/build.js @@ -1,54 +1,62 @@ -var fs = require('fs') -var path = require('path') -var rollup = require('rollup') -var babel = require('rollup-plugin-babel') -var uglify = require('rollup-plugin-uglify') -var version = process.env.VERSION || require('./package.json').version - -var banner = - '/*!\n' + - ' * Vue-Lazyload.js v' + version + '\n' + - ' * (c) ' + new Date().getFullYear() + ' Awe \n' + - ' * Released under the MIT License.\n' + - ' */\n' - -rollup.rollup({ - entry: path.resolve(__dirname, 'src/index.js'), - plugins: [ - babel(), - uglify() - ] -}) -.then(bundle => { - return write(path.resolve(__dirname, 'vue-lazyload.js'), rewriteVersion(bundle.generate({ - format: 'umd', - moduleName: 'VueLazyload' - }).code)) -}) -.then(() => { - console.log('Vue-Lazyload.js v' + version + ' builded') -}) -.catch(console.log) - -function rewriteVersion (code) { - return code.replace('__VUE_LAZYLOAD_VERSION__', version) +const fs = require('fs') +const path = require('path') +const rollup = require('rollup') +const babel = require('rollup-plugin-babel') +const uglify = require('rollup-plugin-uglify') +const version = process.env.VERSION || require('./package.json').version + +const banner = + '/*!\n' + + ' * Vue-Lazyload.js v' + version + '\n' + + ' * (c) ' + new Date().getFullYear() + ' Awe \n' + + ' * Released under the MIT License.\n' + + ' */\n' +async function build() { + try { + const bundle = await rollup.rollup({ + input: path.resolve(__dirname, 'src/index.js'), + plugins: [ + babel(), + uglify() + ] + }) + + let { code } = await bundle.generate({ + format: 'umd', + name: 'VueLazyload' + }) + + code = rewriteVersion(code) + + await write(path.resolve(__dirname, 'vue-lazyload.js'), code) + + console.log('Vue-Lazyload.js v' + version + ' builded') + } catch (e) { + console.log(e) + } +} + +function rewriteVersion(code) { + return code.replace('__VUE_LAZYLOAD_VERSION__', version) } -function getSize (code) { - return (code.length / 1024).toFixed(2) + 'kb' +function getSize(code) { + return (code.length / 1024).toFixed(2) + 'kb' } -function blue (str) { - return '\x1b[1m\x1b[34m' + str + '\x1b[39m\x1b[22m' +function blue(str) { + return '\x1b[1m\x1b[34m' + str + '\x1b[39m\x1b[22m' } -function write (dest, code) { - return new Promise(function (resolve, reject) { - code = banner + code - fs.writeFile(dest, code, function (err) { - if (err) return reject(err) - console.log(blue(dest) + ' ' + getSize(code)) - resolve() +function write(dest, code) { + return new Promise(function (resolve, reject) { + code = banner + code + fs.writeFile(dest, code, function (err) { + if (err) return reject(err) + console.log(blue(dest) + ' ' + getSize(code)) + resolve() + }) }) - }) } + +build() diff --git a/package.json b/package.json index 13a67f0..a78a196 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "unpkg": "vue-lazyload.js", "scripts": { "start": "node build", - "compile": "babel --presets es2015 -d lib/ src/", + "compile": "babel --presets env -d lib/ src/", "test": "npm run compile && mocha --compilers js:babel-core/register" }, "dependencies": {}, @@ -26,19 +26,18 @@ }, "license": "MIT", "devDependencies": { - "babel-cli": "^6.14.0", - "babel-core": "^6.25.0", + "babel-cli": "^6.26.0", + "babel-core": "^6.26.0", "babel-plugin-external-helpers": "^6.22.0", - "babel-polyfill": "^6.13.0", - "babel-preset-es2015": "^6.22.0", - "babel-preset-es2015-rollup": "^1.2.0", + "babel-polyfill": "^6.26.0", + "babel-preset-env": "^1.6.1", "babel-preset-stage-0": "^6.24.1", - "babel-register": "^6.24.1", - "chai": "^4.1.0", - "mocha": "^3.4.2", - "rollup": "^0.35.10", - "rollup-plugin-babel": "^2.6.1", - "rollup-plugin-uglify": "^1.0.1", - "vue": "^2.4.1" + "babel-register": "^6.26.0", + "chai": "^4.1.2", + "mocha": "^4.0.1", + "rollup": "^0.52.1", + "rollup-plugin-babel": "^3.0.2", + "rollup-plugin-uglify": "^2.0.1", + "vue": "^2.5.9" } } diff --git a/vue-lazyload.js b/vue-lazyload.js index 4cf7efb..08fae7b 100644 --- a/vue-lazyload.js +++ b/vue-lazyload.js @@ -3,4 +3,4 @@ * (c) 2017 Awe * Released under the MIT License. */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.VueLazyload=t()}(this,function(){"use strict";function e(e,t){if(e.length){var n=e.indexOf(t);return n>-1?e.splice(n,1):void 0}}function t(e,t){if(!e||!t)return e||{};if(e instanceof Object)for(var n in t)e[n]=t[n];return e}function n(e,t){for(var n=!1,r=0,i=e.length;rt[0])return 1;if(e[0]===t[0]){if(-1!==t[1].indexOf(".webp",t[1].length-5))return 1;if(-1!==e[1].indexOf(".webp",e[1].length-5))return-1}return 0});for(var l="",d=void 0,h=r.length,c=0;c=o){l=d[1];break}return l}}function i(e,t){for(var n=void 0,r=0,i=e.length;r=t?a():n=setTimeout(a,t)}}}function a(e){return null!==e&&"object"===(void 0===e?"undefined":h(e))}function u(e){if(!(e instanceof Object))return[];if(Object.keys)return Object.keys(e);var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n);return t}function l(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function d(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},c="undefined"!=typeof window,f=c&&"IntersectionObserver"in window,v={event:"event",observer:"observer"},p=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;return c&&window.devicePixelRatio||e},g=function(){if(c){var e=!1;try{var t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",null,t)}catch(e){}return e}}(),y={on:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];g?e.addEventListener(t,n,{capture:r,passive:!0}):e.addEventListener(t,n,r)},off:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];e.removeEventListener(t,n,r)}},b=function(e,t,n){var r=new Image;r.src=e.src,r.onload=function(){t({naturalHeight:r.naturalHeight,naturalWidth:r.naturalWidth,src:r.src})},r.onerror=function(e){n(e)}},m=function(e,t){return"undefined"!=typeof getComputedStyle?getComputedStyle(e,null).getPropertyValue(t):e.style[t]},L=function(e){return m(e,"overflow")+m(e,"overflow-y")+m(e,"overflow-x")},w=function(e){if(c){if(!(e instanceof HTMLElement))return window;for(var t=e;t&&t!==document.body&&t!==document.documentElement&&t.parentNode;){if(/(scroll|auto)/.test(L(t)))return t;t=t.parentNode}return window}},_=function(){function e(e,t){for(var n=0;nthis.options.preLoadTop&&this.rect.left0}},{key:"filter",value:function(){var e=this;u(this.options.filter).map(function(t){e.options.filter[t](e,e.options)})}},{key:"renderLoading",value:function(e){var t=this;b({src:this.loading},function(n){t.render("loading",!1),e()},function(n){e(),t.options.silent||console.warn("VueLazyload log: load failed with loading image("+t.loading+")")})}},{key:"load",value:function(){var e=this;return this.attempt>this.options.attempt-1&&this.state.error?void(this.options.silent||console.log("VueLazyload log: "+this.src+" tried too more than "+this.options.attempt+" times")):this.state.loaded||k[this.src]?(this.state.loaded=!0,this.render("loaded",!0)):void this.renderLoading(function(){e.attempt++,e.record("loadStart"),b({src:e.src},function(t){e.naturalHeight=t.naturalHeight,e.naturalWidth=t.naturalWidth,e.state.loaded=!0,e.state.error=!1,e.record("loadEnd"),e.render("loaded",!1),k[e.src]=1},function(t){e.state.error=!0,e.state.loaded=!1,e.render("error",!1)})})}},{key:"render",value:function(e,t){this.elRenderer(this,e,t)}},{key:"performance",value:function(){var e="loading",t=0;return this.state.loaded&&(e="loaded",t=(this.performanceData.loadEnd-this.performanceData.loadStart)/1e3),this.state.error&&(e="error"),{src:this.src,state:e,time:t}}},{key:"destroy",value:function(){this.el=null,this.src=null,this.error=null,this.loading=null,this.bindType=null,this.attempt=0}}]),e}(),T=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{};t(this.options,e)}},{key:"performance",value:function(){var e=[];return this.ListenerQueue.map(function(t){e.push(t.performance())}),e}},{key:"addLazyBox",value:function(e){this.ListenerQueue.push(e),c&&(this._addListenerTarget(window),this._observer&&this._observer.observe(e.el),e.$el&&e.$el.parentNode&&this._addListenerTarget(e.$el.parentNode))}},{key:"add",value:function(e,t,i){var o=this;if(n(this.ListenerQueue,function(t){return t.el===e}))return this.update(e,t),u.nextTick(this.lazyLoadHandler);var s=this._valueFormatter(t.value),a=s.src,l=s.loading,d=s.error;u.nextTick(function(){a=r(e,o.options.scale)||a,o._observer&&o._observer.observe(e);var n=Object.keys(t.modifiers)[0],s=void 0;n&&(s=i.context.$refs[n],s=s?s.$el||s:document.getElementById(n)),s||(s=w(e));var h=new E({bindType:t.arg,$parent:s,el:e,loading:l,error:d,src:a,elRenderer:o._elRenderer.bind(o),options:o.options});o.ListenerQueue.push(h),c&&(o._addListenerTarget(window),o._addListenerTarget(s)),o.lazyLoadHandler(),u.nextTick(function(){return o.lazyLoadHandler()})})}},{key:"update",value:function(e,t){var n=this,o=this._valueFormatter(t.value),s=o.src,a=o.loading,l=o.error;s=r(e,this.options.scale)||s;var d=i(this.ListenerQueue,function(t){return t.el===e});d&&d.update({src:s,loading:a,error:l}),this._observer&&this._observer.observe(e),this.lazyLoadHandler(),u.nextTick(function(){return n.lazyLoadHandler()})}},{key:"remove",value:function(t){if(t){this._observer&&this._observer.unobserve(t);var n=i(this.ListenerQueue,function(e){return e.el===t});n&&(this._removeListenerTarget(n.$parent),this._removeListenerTarget(window),e(this.ListenerQueue,n)&&n.destroy())}}},{key:"removeComponent",value:function(t){t&&(e(this.ListenerQueue,t),this._observer&&this._observer.unobserve(t.el),t.$parent&&t.$el.parentNode&&this._removeListenerTarget(t.$el.parentNode),this._removeListenerTarget(window))}},{key:"setMode",value:function(e){var t=this;f||e!==v.observer||(e=v.event),this.mode=e,e===v.event?(this._observer&&(this.ListenerQueue.forEach(function(e){t._observer.unobserve(e.el)}),this._observer=null),this.TargetQueue.forEach(function(e){t._initListen(e.el,!0)})):(this.TargetQueue.forEach(function(e){t._initListen(e.el,!1)}),this._initIntersectionObserver())}},{key:"_addListenerTarget",value:function(e){if(e){var t=i(this.TargetQueue,function(t){return t.el===e});return t?t.childrenCount++:(t={el:e,id:++this.TargetIndex,childrenCount:1,listened:!0},this.mode===v.event&&this._initListen(t.el,!0),this.TargetQueue.push(t)),this.TargetIndex}}},{key:"_removeListenerTarget",value:function(e){var t=this;this.TargetQueue.forEach(function(n,r){n.el===e&&(--n.childrenCount||(t._initListen(n.el,!1),t.TargetQueue.splice(r,1),n=null))})}},{key:"_initListen",value:function(e,t){var n=this;this.options.ListenEvents.forEach(function(r){return y[t?"on":"off"](e,r,n.lazyLoadHandler)})}},{key:"_initEvent",value:function(){var t=this;this.Event={listeners:{loading:[],loaded:[],error:[]}},this.$on=function(e,n){t.Event.listeners[e].push(n)},this.$once=function(e,n){function r(){i.$off(e,r),n.apply(i,arguments)}var i=t;t.$on(e,r)},this.$off=function(n,r){if(!r)return void(t.Event.listeners[n]=[]);e(t.Event.listeners[n],r)},this.$emit=function(e,n,r){t.Event.listeners[e].forEach(function(e){return e(n,r)})}}},{key:"_lazyLoadHandler",value:function(){console.log(this);var e=!1;this.ListenerQueue.forEach(function(t){t.state.loaded||(e=t.checkInView())&&t.load()})}},{key:"_initIntersectionObserver",value:function(){var e=this;f&&(this._observer=new IntersectionObserver(this._observerHandler.bind(this),this.options.observerOptions),this.ListenerQueue.length&&this.ListenerQueue.forEach(function(t){e._observer.observe(t.el)}))}},{key:"_observerHandler",value:function(e,t){var n=this;e.forEach(function(e){e.isIntersecting&&n.ListenerQueue.forEach(function(t){if(t.el===e.target){if(t.state.loaded)return n._observer.unobserve(t.el);t.load()}})})}},{key:"_elRenderer",value:function(e,t,n){if(e.el){var r=e.el,i=e.bindType,o=void 0;switch(t){case"loading":o=e.loading;break;case"error":o=e.error;break;default:o=e.src}if(i?r.style[i]="url("+o+")":r.getAttribute("src")!==o&&r.setAttribute("src",o),r.setAttribute("lazy",t),this.$emit(t,e,n),this.options.adapter[t]&&this.options.adapter[t](e,this.options),this.options.dispatchEvent){var s=new CustomEvent(t,{detail:e});r.dispatchEvent(s)}}}},{key:"_valueFormatter",value:function(e){var t=e,n=this.options.loading,r=this.options.error;return a(e)&&(e.src||this.options.silent||console.error("Vue Lazyload warning: miss src with "+e),t=e.src,n=e.loading||this.options.loading,r=e.error||this.options.error),{src:t,loading:n,error:r}}}]),l}()},O=function(e){return{props:{tag:{type:String,default:"div"}},render:function(e){return!1===this.show?e(this.tag):e(this.tag,null,this.$slots.default)},data:function(){return{el:null,state:{loaded:!1},rect:{},show:!1}},mounted:function(){this.el=this.$el,e.addLazyBox(this),e.lazyLoadHandler()},beforeDestroy:function(){e.removeComponent(this)},methods:{getRect:function(){this.rect=this.$el.getBoundingClientRect()},checkInView:function(){return this.getRect(),c&&this.rect.top0&&this.rect.left0},load:function(){this.show=!0,this.state.loaded=!0,this.$emit("show",this)}}}};return{install:function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=H(e),i=new r(n),o="2"===e.version.split(".")[0];e.prototype.$Lazyload=i,n.lazyComponent&&e.component("lazy-component",O(i)),o?e.directive("lazy",{bind:i.add.bind(i),update:i.update.bind(i),componentUpdated:i.lazyLoadHandler.bind(i),unbind:i.remove.bind(i)}):e.directive("lazy",{bind:i.lazyLoadHandler.bind(i),update:function(e,n){t(this.vm.$refs,this.vm.$els),i.add(this.el,{modifiers:this.modifiers||{},arg:this.arg,value:e,oldValue:n},{context:this.vm})},unbind:function(){i.remove(this.el)}})}}}); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.VueLazyload=t()}(this,function(){"use strict";function e(e,t){if(e.length){var n=e.indexOf(t);return n>-1?e.splice(n,1):void 0}}function t(e,t){if(!e||!t)return e||{};if(e instanceof Object)for(var n in t)e[n]=t[n];return e}function n(e,t){if("IMG"===e.tagName&&e.getAttribute("data-srcset")){var n=e.getAttribute("data-srcset"),r=[],i=e.parentNode.offsetWidth*t,o=void 0,s=void 0,a=void 0;(n=n.trim().split(",")).map(function(e){e=e.trim(),-1===(o=e.lastIndexOf(" "))?(s=e,a=999998):(s=e.substr(0,o),a=parseInt(e.substr(o+1,e.length-o-2),10)),r.push([a,s])}),r.sort(function(e,t){if(e[0]t[0])return 1;if(e[0]===t[0]){if(-1!==t[1].indexOf(".webp",t[1].length-5))return 1;if(-1!==e[1].indexOf(".webp",e[1].length-5))return-1}return 0});for(var u="",l=void 0,d=r.length,h=0;h=i){u=l[1];break}return u}}function r(e,t){for(var n=void 0,r=0,i=e.length;r0&&void 0!==arguments[0]?arguments[0]:1;return o&&window.devicePixelRatio||e},l=function(){if(o){var e=!1;try{var t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",null,t)}catch(e){}return e}}(),d={on:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];l?e.addEventListener(t,n,{capture:r,passive:!0}):e.addEventListener(t,n,r)},off:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];e.removeEventListener(t,n,r)}},h=function(e,t,n){var r=new Image;r.src=e.src,r.onload=function(){t({naturalHeight:r.naturalHeight,naturalWidth:r.naturalWidth,src:r.src})},r.onerror=function(e){n(e)}},c=function(e,t){return"undefined"!=typeof getComputedStyle?getComputedStyle(e,null).getPropertyValue(t):e.style[t]},f=function(e){return c(e,"overflow")+c(e,"overflow-y")+c(e,"overflow-x")},v=function(){function e(e,t){for(var n=0;nthis.options.preLoadTop&&this.rect.left0}},{key:"filter",value:function(){var e=this;(function(e){if(!(e instanceof Object))return[];if(Object.keys)return Object.keys(e);var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n);return t})(this.options.filter).map(function(t){e.options.filter[t](e,e.options)})}},{key:"renderLoading",value:function(e){var t=this;h({src:this.loading},function(n){t.render("loading",!1),e()},function(n){e(),t.options.silent||console.warn("VueLazyload log: load failed with loading image("+t.loading+")")})}},{key:"load",value:function(){var e=this;{if(!(this.attempt>this.options.attempt-1&&this.state.error))return this.state.loaded||p[this.src]?(this.state.loaded=!0,this.render("loaded",!0)):void this.renderLoading(function(){e.attempt++,e.record("loadStart"),h({src:e.src},function(t){e.naturalHeight=t.naturalHeight,e.naturalWidth=t.naturalWidth,e.state.loaded=!0,e.state.error=!1,e.record("loadEnd"),e.render("loaded",!1),p[e.src]=1},function(t){e.state.error=!0,e.state.loaded=!1,e.render("error",!1)})});this.options.silent||console.log("VueLazyload log: "+this.src+" tried too more than "+this.options.attempt+" times")}}},{key:"render",value:function(e,t){this.elRenderer(this,e,t)}},{key:"performance",value:function(){var e="loading",t=0;return this.state.loaded&&(e="loaded",t=(this.performanceData.loadEnd-this.performanceData.loadStart)/1e3),this.state.error&&(e="error"),{src:this.src,state:e,time:t}}},{key:"destroy",value:function(){this.el=null,this.src=null,this.error=null,this.loading=null,this.bindType=null,this.attempt=0}}]),e}(),y=function(){function e(e,t){for(var n=0;n=t?s():n=setTimeout(s,t)}}}(this._lazyLoadHandler.bind(this),this.options.throttleWait),this.setMode(this.options.observer?a.observer:a.event)}return y(h,[{key:"config",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t(this.options,e)}},{key:"performance",value:function(){var e=[];return this.ListenerQueue.map(function(t){e.push(t.performance())}),e}},{key:"addLazyBox",value:function(e){this.ListenerQueue.push(e),o&&(this._addListenerTarget(window),this._observer&&this._observer.observe(e.el),e.$el&&e.$el.parentNode&&this._addListenerTarget(e.$el.parentNode))}},{key:"add",value:function(e,t,r){var i=this;if(function(e,t){for(var n=!1,r=0,i=e.length;r1&&void 0!==arguments[1]?arguments[1]:{},r=new(w(e))(n),i="2"===e.version.split(".")[0];e.prototype.$Lazyload=r,n.lazyComponent&&e.component("lazy-component",function(e){return{props:{tag:{type:String,default:"div"}},render:function(e){return!1===this.show?e(this.tag):e(this.tag,null,this.$slots.default)},data:function(){return{el:null,state:{loaded:!1},rect:{},show:!1}},mounted:function(){this.el=this.$el,e.addLazyBox(this),e.lazyLoadHandler()},beforeDestroy:function(){e.removeComponent(this)},methods:{getRect:function(){this.rect=this.$el.getBoundingClientRect()},checkInView:function(){return this.getRect(),o&&this.rect.top0&&this.rect.left0},load:function(){this.show=!0,this.state.loaded=!0,this.$emit("show",this)}}}}(r)),i?e.directive("lazy",{bind:r.add.bind(r),update:r.update.bind(r),componentUpdated:r.lazyLoadHandler.bind(r),unbind:r.remove.bind(r)}):e.directive("lazy",{bind:r.lazyLoadHandler.bind(r),update:function(e,n){t(this.vm.$refs,this.vm.$els),r.add(this.el,{modifiers:this.modifiers||{},arg:this.arg,value:e,oldValue:n},{context:this.vm})},unbind:function(){r.remove(this.el)}})}}}); From 3d6e4eb4f1be83cde8f941ae58fbf48a806f150d Mon Sep 17 00:00:00 2001 From: yugasun Date: Mon, 11 Dec 2017 15:23:58 +0800 Subject: [PATCH 3/4] update babel config --- .babelrc | 3 --- build.js | 5 ++++- package.json | 2 +- test/tests.js | 2 +- vue-lazyload.js | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.babelrc b/.babelrc index fe1d213..3ed94df 100644 --- a/.babelrc +++ b/.babelrc @@ -1,8 +1,5 @@ { "presets": [ ["env", { "modules": false }] - ], - "plugins": [ - "external-helpers" ] } diff --git a/build.js b/build.js index 874e0e1..e0ce76b 100644 --- a/build.js +++ b/build.js @@ -16,7 +16,10 @@ async function build() { const bundle = await rollup.rollup({ input: path.resolve(__dirname, 'src/index.js'), plugins: [ - babel(), + babel({ + exclude: 'node_modules/**', + plugins: ['external-helpers'] + }), uglify() ] }) diff --git a/package.json b/package.json index a78a196..a24fd49 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "scripts": { "start": "node build", "compile": "babel --presets env -d lib/ src/", - "test": "npm run compile && mocha --compilers js:babel-core/register" + "test": "npm run compile && mocha --require babel-core/register" }, "dependencies": {}, "repository": { diff --git a/test/tests.js b/test/tests.js index 00346de..a0a05d8 100644 --- a/test/tests.js +++ b/test/tests.js @@ -58,4 +58,4 @@ describe('VueLazyload.js Test Suite', function () { // expect(vm.$Lazyload.TargetQueue.length).to.equal(0) // }) -}) \ No newline at end of file +}) diff --git a/vue-lazyload.js b/vue-lazyload.js index 08fae7b..bd66499 100644 --- a/vue-lazyload.js +++ b/vue-lazyload.js @@ -3,4 +3,4 @@ * (c) 2017 Awe * Released under the MIT License. */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.VueLazyload=t()}(this,function(){"use strict";function e(e,t){if(e.length){var n=e.indexOf(t);return n>-1?e.splice(n,1):void 0}}function t(e,t){if(!e||!t)return e||{};if(e instanceof Object)for(var n in t)e[n]=t[n];return e}function n(e,t){if("IMG"===e.tagName&&e.getAttribute("data-srcset")){var n=e.getAttribute("data-srcset"),r=[],i=e.parentNode.offsetWidth*t,o=void 0,s=void 0,a=void 0;(n=n.trim().split(",")).map(function(e){e=e.trim(),-1===(o=e.lastIndexOf(" "))?(s=e,a=999998):(s=e.substr(0,o),a=parseInt(e.substr(o+1,e.length-o-2),10)),r.push([a,s])}),r.sort(function(e,t){if(e[0]t[0])return 1;if(e[0]===t[0]){if(-1!==t[1].indexOf(".webp",t[1].length-5))return 1;if(-1!==e[1].indexOf(".webp",e[1].length-5))return-1}return 0});for(var u="",l=void 0,d=r.length,h=0;h=i){u=l[1];break}return u}}function r(e,t){for(var n=void 0,r=0,i=e.length;r0&&void 0!==arguments[0]?arguments[0]:1;return o&&window.devicePixelRatio||e},l=function(){if(o){var e=!1;try{var t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",null,t)}catch(e){}return e}}(),d={on:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];l?e.addEventListener(t,n,{capture:r,passive:!0}):e.addEventListener(t,n,r)},off:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];e.removeEventListener(t,n,r)}},h=function(e,t,n){var r=new Image;r.src=e.src,r.onload=function(){t({naturalHeight:r.naturalHeight,naturalWidth:r.naturalWidth,src:r.src})},r.onerror=function(e){n(e)}},c=function(e,t){return"undefined"!=typeof getComputedStyle?getComputedStyle(e,null).getPropertyValue(t):e.style[t]},f=function(e){return c(e,"overflow")+c(e,"overflow-y")+c(e,"overflow-x")},v=function(){function e(e,t){for(var n=0;nthis.options.preLoadTop&&this.rect.left0}},{key:"filter",value:function(){var e=this;(function(e){if(!(e instanceof Object))return[];if(Object.keys)return Object.keys(e);var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n);return t})(this.options.filter).map(function(t){e.options.filter[t](e,e.options)})}},{key:"renderLoading",value:function(e){var t=this;h({src:this.loading},function(n){t.render("loading",!1),e()},function(n){e(),t.options.silent||console.warn("VueLazyload log: load failed with loading image("+t.loading+")")})}},{key:"load",value:function(){var e=this;{if(!(this.attempt>this.options.attempt-1&&this.state.error))return this.state.loaded||p[this.src]?(this.state.loaded=!0,this.render("loaded",!0)):void this.renderLoading(function(){e.attempt++,e.record("loadStart"),h({src:e.src},function(t){e.naturalHeight=t.naturalHeight,e.naturalWidth=t.naturalWidth,e.state.loaded=!0,e.state.error=!1,e.record("loadEnd"),e.render("loaded",!1),p[e.src]=1},function(t){e.state.error=!0,e.state.loaded=!1,e.render("error",!1)})});this.options.silent||console.log("VueLazyload log: "+this.src+" tried too more than "+this.options.attempt+" times")}}},{key:"render",value:function(e,t){this.elRenderer(this,e,t)}},{key:"performance",value:function(){var e="loading",t=0;return this.state.loaded&&(e="loaded",t=(this.performanceData.loadEnd-this.performanceData.loadStart)/1e3),this.state.error&&(e="error"),{src:this.src,state:e,time:t}}},{key:"destroy",value:function(){this.el=null,this.src=null,this.error=null,this.loading=null,this.bindType=null,this.attempt=0}}]),e}(),y=function(){function e(e,t){for(var n=0;n=t?s():n=setTimeout(s,t)}}}(this._lazyLoadHandler.bind(this),this.options.throttleWait),this.setMode(this.options.observer?a.observer:a.event)}return y(h,[{key:"config",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t(this.options,e)}},{key:"performance",value:function(){var e=[];return this.ListenerQueue.map(function(t){e.push(t.performance())}),e}},{key:"addLazyBox",value:function(e){this.ListenerQueue.push(e),o&&(this._addListenerTarget(window),this._observer&&this._observer.observe(e.el),e.$el&&e.$el.parentNode&&this._addListenerTarget(e.$el.parentNode))}},{key:"add",value:function(e,t,r){var i=this;if(function(e,t){for(var n=!1,r=0,i=e.length;r1&&void 0!==arguments[1]?arguments[1]:{},r=new(w(e))(n),i="2"===e.version.split(".")[0];e.prototype.$Lazyload=r,n.lazyComponent&&e.component("lazy-component",function(e){return{props:{tag:{type:String,default:"div"}},render:function(e){return!1===this.show?e(this.tag):e(this.tag,null,this.$slots.default)},data:function(){return{el:null,state:{loaded:!1},rect:{},show:!1}},mounted:function(){this.el=this.$el,e.addLazyBox(this),e.lazyLoadHandler()},beforeDestroy:function(){e.removeComponent(this)},methods:{getRect:function(){this.rect=this.$el.getBoundingClientRect()},checkInView:function(){return this.getRect(),o&&this.rect.top0&&this.rect.left0},load:function(){this.show=!0,this.state.loaded=!0,this.$emit("show",this)}}}}(r)),i?e.directive("lazy",{bind:r.add.bind(r),update:r.update.bind(r),componentUpdated:r.lazyLoadHandler.bind(r),unbind:r.remove.bind(r)}):e.directive("lazy",{bind:r.lazyLoadHandler.bind(r),update:function(e,n){t(this.vm.$refs,this.vm.$els),r.add(this.el,{modifiers:this.modifiers||{},arg:this.arg,value:e,oldValue:n},{context:this.vm})},unbind:function(){r.remove(this.el)}})}}}); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.VueLazyload=t()}(this,function(){"use strict";function e(e,t){if(e.length){var n=e.indexOf(t);return n>-1?e.splice(n,1):void 0}}function t(e,t){if(!e||!t)return e||{};if(e instanceof Object)for(var n in t)e[n]=t[n];return e}function n(e,t){if("IMG"===e.tagName&&e.getAttribute("data-srcset")){var n=e.getAttribute("data-srcset"),i=[],r=e.parentNode.offsetWidth*t,o=void 0,s=void 0,a=void 0;(n=n.trim().split(",")).map(function(e){e=e.trim(),-1===(o=e.lastIndexOf(" "))?(s=e,a=999998):(s=e.substr(0,o),a=parseInt(e.substr(o+1,e.length-o-2),10)),i.push([a,s])}),i.sort(function(e,t){if(e[0]t[0])return 1;if(e[0]===t[0]){if(-1!==t[1].indexOf(".webp",t[1].length-5))return 1;if(-1!==e[1].indexOf(".webp",e[1].length-5))return-1}return 0});for(var u="",l=void 0,d=i.length,h=0;h=r){u=l[1];break}return u}}function i(e,t){for(var n=void 0,i=0,r=e.length;i0&&void 0!==arguments[0]?arguments[0]:1;return a&&window.devicePixelRatio||e},h=function(){if(a){var e=!1;try{var t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",null,t)}catch(e){}return e}}(),c={on:function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];h?e.addEventListener(t,n,{capture:i,passive:!0}):e.addEventListener(t,n,i)},off:function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];e.removeEventListener(t,n,i)}},f=function(e,t,n){var i=new Image;i.src=e.src,i.onload=function(){t({naturalHeight:i.naturalHeight,naturalWidth:i.naturalWidth,src:i.src})},i.onerror=function(e){n(e)}},v=function(e,t){return"undefined"!=typeof getComputedStyle?getComputedStyle(e,null).getPropertyValue(t):e.style[t]},p=function(e){return v(e,"overflow")+v(e,"overflow-y")+v(e,"overflow-x")},g={},y=function(){function e(t){var n=t.el,i=t.src,r=t.error,s=t.loading,a=t.bindType,u=t.$parent,l=t.options,d=t.elRenderer;o(this,e),this.el=n,this.src=i,this.error=r,this.loading=s,this.bindType=a,this.attempt=0,this.naturalHeight=0,this.naturalWidth=0,this.options=l,this.filter(),this.initState(),this.performanceData={init:Date.now(),loadStart:null,loadEnd:null},this.rect=n.getBoundingClientRect(),this.$parent=u,this.elRenderer=d,this.render("loading",!1)}return s(e,[{key:"initState",value:function(){this.state={error:!1,loaded:!1,rendered:!1}}},{key:"record",value:function(e){this.performanceData[e]=Date.now()}},{key:"update",value:function(e){var t=e.src,n=e.loading,i=e.error,r=this.src;this.src=t,this.loading=n,this.error=i,this.filter(),r!==this.src&&(this.attempt=0,this.initState())}},{key:"getRect",value:function(){this.rect=this.el.getBoundingClientRect()}},{key:"checkInView",value:function(){return this.getRect(),this.rect.topthis.options.preLoadTop&&this.rect.left0}},{key:"filter",value:function(){var e=this;(function(e){if(!(e instanceof Object))return[];if(Object.keys)return Object.keys(e);var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n);return t})(this.options.filter).map(function(t){e.options.filter[t](e,e.options)})}},{key:"renderLoading",value:function(e){var t=this;f({src:this.loading},function(n){t.render("loading",!1),e()},function(n){e(),t.options.silent||console.warn("VueLazyload log: load failed with loading image("+t.loading+")")})}},{key:"load",value:function(){var e=this;{if(!(this.attempt>this.options.attempt-1&&this.state.error))return this.state.loaded||g[this.src]?(this.state.loaded=!0,this.render("loaded",!0)):void this.renderLoading(function(){e.attempt++,e.record("loadStart"),f({src:e.src},function(t){e.naturalHeight=t.naturalHeight,e.naturalWidth=t.naturalWidth,e.state.loaded=!0,e.state.error=!1,e.record("loadEnd"),e.render("loaded",!1),g[e.src]=1},function(t){e.state.error=!0,e.state.loaded=!1,e.render("error",!1)})});this.options.silent||console.log("VueLazyload log: "+this.src+" tried too more than "+this.options.attempt+" times")}}},{key:"render",value:function(e,t){this.elRenderer(this,e,t)}},{key:"performance",value:function(){var e="loading",t=0;return this.state.loaded&&(e="loaded",t=(this.performanceData.loadEnd-this.performanceData.loadStart)/1e3),this.state.error&&(e="error"),{src:this.src,state:e,time:t}}},{key:"destroy",value:function(){this.el=null,this.src=null,this.error=null,this.loading=null,this.bindType=null,this.attempt=0}}]),e}(),b="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",m=["scroll","wheel","mousewheel","resize","animationend","transitionend","touchmove"],L={rootMargin:"0px",threshold:0},w=function(h){return function(){function f(e){var t=e.preLoad,n=e.error,i=e.throttleWait,r=e.preLoadTop,s=e.dispatchEvent,u=e.loading,h=e.attempt,c=e.silent,v=void 0===c||c,p=e.scale,g=e.listenEvents,y=(e.hasbind,e.filter),w=e.adapter,_=e.observer,k=e.observerOptions;o(this,f),this.version="1.1.4",this.mode=l.event,this.ListenerQueue=[],this.TargetIndex=0,this.TargetQueue=[],this.options={silent:v,dispatchEvent:!!s,throttleWait:i||200,preLoad:t||1.3,preLoadTop:r||0,error:n||b,loading:u||b,attempt:h||3,scale:p||d(p),ListenEvents:g||m,hasbind:!1,supportWebp:function(){if(!a)return!1;var e=!0,t=document;try{var n=t.createElement("object");n.type="image/webp",n.style.visibility="hidden",n.innerHTML="!",t.body.appendChild(n),e=!n.offsetWidth,t.body.removeChild(n)}catch(t){e=!1}return e}(),filter:y||{},adapter:w||{},observer:!!_,observerOptions:k||L},this._initEvent(),this.lazyLoadHandler=function(e,t){var n=null,i=0;return function(){if(!n){var r=this,o=arguments,s=function(){i=Date.now(),n=!1,e.apply(r,o)};Date.now()-i>=t?s():n=setTimeout(s,t)}}}(this._lazyLoadHandler.bind(this),this.options.throttleWait),this.setMode(this.options.observer?l.observer:l.event)}return s(f,[{key:"config",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t(this.options,e)}},{key:"performance",value:function(){var e=[];return this.ListenerQueue.map(function(t){e.push(t.performance())}),e}},{key:"addLazyBox",value:function(e){this.ListenerQueue.push(e),a&&(this._addListenerTarget(window),this._observer&&this._observer.observe(e.el),e.$el&&e.$el.parentNode&&this._addListenerTarget(e.$el.parentNode))}},{key:"add",value:function(e,t,i){var r=this;if(function(e,t){for(var n=!1,i=0,r=e.length;i1&&void 0!==arguments[1]?arguments[1]:{},i=new(w(e))(n),r="2"===e.version.split(".")[0];e.prototype.$Lazyload=i,n.lazyComponent&&e.component("lazy-component",function(e){return{props:{tag:{type:String,default:"div"}},render:function(e){return!1===this.show?e(this.tag):e(this.tag,null,this.$slots.default)},data:function(){return{el:null,state:{loaded:!1},rect:{},show:!1}},mounted:function(){this.el=this.$el,e.addLazyBox(this),e.lazyLoadHandler()},beforeDestroy:function(){e.removeComponent(this)},methods:{getRect:function(){this.rect=this.$el.getBoundingClientRect()},checkInView:function(){return this.getRect(),a&&this.rect.top0&&this.rect.left0},load:function(){this.show=!0,this.state.loaded=!0,this.$emit("show",this)}}}}(i)),r?e.directive("lazy",{bind:i.add.bind(i),update:i.update.bind(i),componentUpdated:i.lazyLoadHandler.bind(i),unbind:i.remove.bind(i)}):e.directive("lazy",{bind:i.lazyLoadHandler.bind(i),update:function(e,n){t(this.vm.$refs,this.vm.$els),i.add(this.el,{modifiers:this.modifiers||{},arg:this.arg,value:e,oldValue:n},{context:this.vm})},unbind:function(){i.remove(this.el)}})}}}); From 8268f089cd3ffacbbe328976efe08281a086d5ae Mon Sep 17 00:00:00 2001 From: yugasun Date: Mon, 11 Dec 2017 15:37:19 +0800 Subject: [PATCH 4/4] add silent option in README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cb8c6ba..1915013 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,7 @@ new Vue({ | `throttleWait`|throttle wait|`200`|`Number`| | `observer`|use IntersectionObserver|`false`|`Boolean`| | `observerOptions`|IntersectionObserver options|{ rootMargin: '0px', threshold: 0.1 }|[IntersectionObserver](#intersectionobserver)| +| `silent`|do not print debug info|`true`|`Boolean`| ### Desired Listen Events @@ -188,7 +189,7 @@ Vue.use(vueLazy, { // optional observerOptions: { - rootMargin: '0px', + rootMargin: '0px', threshold: 0.1 } })