forked from sl1673495/easy-lazyload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheasy-lazyload.js
422 lines (377 loc) · 11.6 KB
/
easy-lazyload.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
(function () {
var DEFAULT_URL = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
var DEFAULT_EVENTS = ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend', 'touchmove']
var hasIntersectionObserver = Boolean(window['IntersectionObserver'])
var supportsPassive = (function () {
var support = false
try {
var opts = Object.defineProperty({}, 'passive', {
get: function () {
support = true
}
})
window.addEventListener('test', null, opts)
} catch (e) { }
return support
})();
var cid = 0
var utils = {
noop: function () { },
arrayFrom: function (arrLike) {
var len = arrLike.length
if (!len || utils.isArray(arrLike)) {
return arrLike
}
var list = []
for (var i = 0; i < len; i++) {
list.push(arrLike[i])
}
return list
},
forEach: function (arr, fn) {
var nativeEach = Array.prototype.forEach
if (nativeEach) {
return nativeEach.call(arr, fn)
} else {
for (var i = 0; i < arr.length; i++) {
fn(arr[i], i)
}
}
},
getDataSet: function (el, attr) {
if ('dataset' in el) {
return el.dataset[attr]
} else {
return el.getAttribute('data-' + attr)
}
},
setDataSet: function (el, attr, value) {
if ('dataset' in el) {
el.dataset[attr] = value
} else {
el.setAttribute('data-' + attr, value)
}
},
style: function (el, prop) {
return typeof getComputedStyle !== 'undefined'
? getComputedStyle(el, null).getPropertyValue(prop)
: el.style[prop]
},
overflow: function (el) {
return utils.style(el, 'overflow') + utils.style(el, 'overflow-y') + utils.style(el, 'overflow-x')
},
isHTMLElement(el) {
return el instanceof HTMLElement
},
isArray(v) {
return v instanceof Array
},
scrollParent: function (el) {
if (!(utils.isHTMLElement(el))) {
return window
}
let parent = el
while (parent) {
if (parent === document.body || parent === document.documentElement) {
break
}
if (!parent.parentNode) {
break
}
if (/(scroll|auto)/.test(utils.overflow(parent))) {
return parent
}
parent = parent.parentNode
}
return window
},
loadImageAsync: function (src, onSuccess, onError) {
onSuccess = onSuccess || utils.noop
onError = onError || utils.noop
var image = new Image()
image.src = src
image.onload = function () {
onSuccess({
naturalHeight: image.naturalHeight,
naturalWidth: image.naturalWidth,
src: image.src
})
}
image.onerror = function (e) {
onError(e)
}
},
throttle: function (action, delay) {
var timeout = null
var lastRun = 0
return function () {
if (timeout) {
return
}
var elapsed = Date.now() - lastRun
var args = arguments
var runCallback = function () {
lastRun = Date.now()
timeout = false
action.apply(null, args)
}
if (elapsed >= delay) {
runCallback()
} else {
timeout = setTimeout(runCallback, delay)
}
}
},
findIndex: function (arr, fn) {
var i, len
for (i = 0, len = arr.length; i < len; i++) {
if (fn(arr[i])) {
break
}
}
return i
},
addEvent: function (node, event, fn, capture) {
capture == utils.isUndef(capture) ? false : capture
if (typeof node.addEventListener == 'function') {
if (supportsPassive) {
node.addEventListener(event, fn, {
capture: capture,
passive: true
})
} else {
node.addEventListener(event, fn, capture)
}
}
else if (typeof node.attachEvent == 'function') {
node.attachEvent('on' + event, fn);
}
},
removeEvent: function (node, event, fn) {
if (typeof node.removeEventListener == 'function') {
node.removeEventListener(event, fn);
}
else if (typeof node.detatchEvent == 'function') {
node.detatchEvent('on' + event, fn);
}
},
isUndef: function (val) {
return val === null || val === undefined
}
}
var Load = function (el, options) {
this._initOptions(options)
this._initProperties(el, options)
this._preLoad()
this._initImageListeners()
this._initEvents()
}
// 规范化配置
Load.prototype._initOptions = function (options) {
options = options || {}
this.options = {
loading: options.loading || DEFAULT_URL,
error: options.error || DEFAULT_URL,
throttleWait: options.throttleWait || 100,
listenEvents: options.listenEvents || DEFAULT_EVENTS,
preLoad: options.preLoad || 1.3,
observer: utils.isUndef(options.observer) ? true : options.observer,
onPreLoad: options.onPreLoad || utils.noop,
beforeMount: options.beforeMount,
mounted: options.mounted,
onLoadMore: options.onLoadMore,
}
}
// 初始化属性
Load.prototype._initProperties = function (el, options) {
this.loadMoreMode = !utils.isUndef(this.options.onLoadMore)
this.el = utils.isHTMLElement(el) ? el : document.querySelector(el)
if (!this.el) {
if (this.loadMoreMode) {
throw new Error('loadMore should bind a mounted dom')
} else {
this.el = document.body
}
}
this.imageListeners = []
this.imageListenersMap = {}
this.lazyloadHandler = null
this._eventBindEl = null
this._eventBindElRect = null
}
// 预加载loading和error图
Load.prototype._preLoad = function () {
if (this.loadMoreMode) return
var ctx = this
var loading = ctx.options.loading
var error = ctx.options.error
utils.loadImageAsync(loading, function () {
ctx._callHook('onPreLoad')
})
utils.loadImageAsync(error)
}
// 加载图片监听类
Load.prototype._initImageListeners = function () {
var ctx = this
var targets = this.loadMoreMode
? [ctx.el]
: ctx.el.querySelectorAll('img')
if (!targets || !targets.length) return
var targetArr = utils.arrayFrom(targets)
utils.forEach(targetArr, function (target) {
if (
(utils.getDataSet(target, 'src') && !ctx.imageListenersMap[utils.getDataSet(target, 'id')]) ||
ctx.loadMoreMode
) {
var listener = new ImageListener(target, ctx.options, ctx)
if (!ctx.loadMoreMode) {
listener.render('loading')
}
var targetId = ++cid
utils.setDataSet(target, 'id', targetId)
ctx.imageListeners.push(listener)
ctx.imageListenersMap[targetId] = listener
}
})
}
// 加载事件
Load.prototype._initEvents = function () {
// 优先采用IntersectionObserver
if (hasIntersectionObserver && this.options.observer) {
this._initIntersectionObserver()
} else {
this._initNormalEvents()
}
}
Load.prototype._initIntersectionObserver = function () {
var ctx = this
ctx._observer = new IntersectionObserver(ctx._observerHandler.bind(ctx), {
rootMargin: window.innerHeight * (ctx.options.preLoad - 1) + 'px' + ' ' + window.innerWidth * (ctx.options.preLoad - 1) + 'px'
})
utils.forEach(ctx.imageListeners, function (imageListener) {
ctx._observer.observe(imageListener.el)
})
}
Load.prototype._observerHandler = function (entries, observer) {
var ctx = this
utils.forEach(entries, function (entry) {
// fixed: 低版本安卓浏览器没有isIntersecting属性
var isEnter = utils.isUndef(entry.isIntersecting) ? entry.intersectionRatio : entry.isIntersecting
if (isEnter) {
var img = entry.target
var imgId = utils.getDataSet(img, 'id')
var listener = ctx.imageListenersMap[imgId]
listener.load()
}
})
}
// 降级方案, 监听事件去判断图片是否进入视口
Load.prototype._initNormalEvents = function () {
var ctx = this
ctx.lazyloadHandler = utils.throttle(this._lazyloadHandler.bind(this), this.options.throttleWait)
var scrollEl = utils.scrollParent(ctx.el)
utils.forEach(DEFAULT_EVENTS, function (eventName) {
utils.addEvent(scrollEl, eventName, ctx.lazyloadHandler)
})
ctx._eventBindEl = scrollEl
ctx._eventBindElRect = utils.isHTMLElement(scrollEl) ? scrollEl.getBoundingClientRect() : document.body.getBoundingClientRect()
ctx.lazyloadHandler()
}
Load.prototype._lazyloadHandler = function () {
var ctx = this
utils.forEach(ctx.imageListeners, function (image) {
if (image.checkInView()) {
image.load()
}
})
}
Load.prototype._callHook = function (hook) {
var hookCallback = this.options[hook]
var argumentsArr = utils.arrayFrom(arguments)
hookCallback.apply(null, argumentsArr.slice(1))
}
// api 用于dom移除后删除事件监听
Load.prototype.destroy = function () {
var ctx = this
if (ctx._observer) {
ctx._observer.disconnect()
} else {
utils.forEach(DEFAULT_EVENTS, function (eventName) {
utils.removeEvent(ctx._eventBindEl, eventName, ctx.lazyloadHandler)
})
}
}
// api 用于添加新图片
Load.prototype.refresh = function () {
this._initImageListeners()
this._initEvents()
}
var ImageListener = function (img, options, loadInstance) {
this.el = img
this.src = utils.getDataSet(img, 'src')
this.options = options
this.rect = null
this.loading = false
this.loaded = false
this.loadInstance = loadInstance
}
ImageListener.prototype.render = function (state, src) {
// loading, error, success
this.el.setAttribute('src', src || this.options[state])
}
ImageListener.prototype.load = function () {
var ctx = this
if (ctx.loading || ctx.loaded) return
ctx.loading = true
if (ctx.loadInstance.loadMoreMode) {
var done = function () {
ctx.loading = false
}
ctx.loadInstance.options.onLoadMore(done)
} else {
utils.loadImageAsync(
this.src,
function onSuccess(result) {
var beforeMount = ctx.loadInstance.options.beforeMount
if (beforeMount) {
ctx.loadInstance._callHook('beforeMount', ctx.el)
// beforeMount可以设置动画的一些初始值,需要手动触发一次重绘
ctx.el.offsetTop
}
var src = result.src
ctx.render('success', src)
if (ctx.loadInstance.options.mounted) {
ctx.loadInstance._callHook('mounted', ctx.el)
}
ctx.finishLoading()
},
function onError() {
ctx.render('error')
ctx.finishLoading()
}
)
}
}
ImageListener.prototype.finishLoading = function () {
var ctx = this
ctx.loading = false
ctx.loaded = true
var sources = ctx.loadInstance.imageListeners
var index = utils.findIndex(sources, function (listener) {
return utils.getDataSet(listener.el, 'id') === utils.getDataSet(ctx.el, 'id')
})
sources.splice(index, 1)
if (ctx.loadInstance._observer) {
ctx.loadInstance._observer.unobserve(ctx.el)
}
}
ImageListener.prototype.getRect = function () {
this.rect = this.el.getBoundingClientRect()
}
ImageListener.prototype.checkInView = function () {
this.getRect()
return (this.rect.top < window.innerHeight * this.options.preLoad) &&
(this.rect.left < window.innerWidth * this.options.preLoad && this.rect.right > 0)
}
window.EasyLazyLoad = Load
})()