-
Notifications
You must be signed in to change notification settings - Fork 158
/
lazyload.js
109 lines (86 loc) · 2.33 KB
/
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
module.exports = lazyload;
var inViewport = require('in-viewport');
var lazyAttrs = ['data-src'];
global.lzld = lazyload();
// Provide libs using getAttribute early to get the good src
// and not the fake data-src
replaceGetAttribute('Image');
replaceGetAttribute('IFrame');
function registerLazyAttr(attr) {
if (indexOf.call(lazyAttrs, attr) === -1) {
lazyAttrs.push(attr);
}
}
function lazyload(opts) {
opts = merge({
'offset': 333,
'src': 'data-src',
'container': false
}, opts || {});
if (typeof opts.src === 'string') {
registerLazyAttr(opts.src);
}
var elts = [];
function show(elt) {
var src = findRealSrc(elt);
if (src) {
elt.src = src;
}
elt.setAttribute('data-lzled', true);
elts[indexOf.call(elts, elt)] = null;
}
function findRealSrc(elt) {
if (typeof opts.src === 'function') {
return opts.src(elt);
}
return elt.getAttribute(opts.src);
}
function register(elt) {
// unsubscribe onload
// needed by IE < 9, otherwise we get another onload when changing the src
elt.onload = null;
elt.removeAttribute('onload');
// https://github.com/vvo/lazyload/issues/62
elt.onerror = null;
elt.removeAttribute('onerror');
if (indexOf.call(elts, elt) === -1) {
inViewport(elt, opts, show);
}
}
return register;
}
function replaceGetAttribute(elementName) {
var fullname = 'HTML' + elementName + 'Element';
if (fullname in global === false) {
return;
}
var original = global[fullname].prototype.getAttribute;
global[fullname].prototype.getAttribute = function(name) {
if (name === 'src') {
var realSrc;
for (var i = 0, max = lazyAttrs.length; i < max; i++) {
realSrc = original.call(this, lazyAttrs[i]);
if (realSrc) {
break;
}
}
return realSrc || original.call(this, name);
}
// our own lazyloader will go through theses lines
// because we use getAttribute(opts.src)
return original.call(this, name);
};
}
function merge(defaults, opts) {
for (var name in defaults) {
if (opts[name] === undefined) {
opts[name] = defaults[name];
}
}
return opts;
}
// http://webreflection.blogspot.fr/2011/06/partial-polyfills.html
function indexOf(value) {
for (var i = this.length; i-- && this[i] !== value;) {}
return i;
}