-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlazy-img.html
217 lines (182 loc) · 6.7 KB
/
lazy-img.html
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
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../poly-poly/poly-poly.html">
<!--
`lazy-img`
Lazy loading img element, delays loading images until they come into the viewport
@demo demo/index.html
-->
<dom-module id="lazy-img">
<template>
<style>
:host {
display: inline-block;
overflow: hidden;
position: relative;
}
img {
display: block;
width: var(--lazy-img-width, auto);
height: var(--lazy-img-height, auto);
@apply(--lazy-img);
}
img.loaded {
@apply(--lazy-img-loaded);
}
</style>
<img id="img" alt="[[alt]]">
</template>
<script>
(function() {
'use strict';
var elementObservers = new WeakMap();
function notifyEntries(entries){
for(var i = 0; i < entries.length; i++) {
entries[i].target._load();
}
}
var blankSrc = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
var polypoly = /** @type {!PolyPolyElement} */ document.createElement('poly-poly');
Polymer({
is: 'lazy-img',
properties: {
/** The source URL for the image */
src: {
type: String,
observer: '_onSrcChanged'
},
/** The alt attribute for the image */
alt: {
type: String
},
/** The root selector for the observer */
observe: {
type: String
},
/**
* The offset applied to the root's bounding_box when calculating
* intersections, effectively shrinking or growing the root for any
* calculation purposes. Supports pixels ('px') or percentages ('%').
*/
margin: {
type: String,
value: '0px 0px 0px 0px'
},
/**
* The ratio of intersection needed to trigger loading. 0 means any
* pixel, 50 means 50% (half the image) needs to be within the root
* target, 100 means the image has to be completely within the view.
*/
threshold: {
type: Number,
value: 0.0
}
},
/** cleanup observers when detached */
detached: function() {
this._stopObserving();
},
/** setting or changing the image src resets the state */
_onSrcChanged: function(src) {
this.$.img.src = blankSrc;
this._stopObserving();
// why do we have this delay? well apart from the delay being the
// whole point of lazy loading images, it also helps if child nodes
// of a scroller are being repositioned in some way (e.g. by some
// layour element). Without this, the nodes might be immediately
// in view of the IntersectionObserver which would trigger loading.
Polymer.RenderStatus.afterNextRender(this, this._startObserving);
},
/** load the image, any loading effects will be provided by the css mixin */
_load: function() {
var img = this.$.img;
img.onload = function() {
img.classList.add('loaded');
};
img.src = this._resolveSrc(this.src);
this._stopObserving();
},
/** stop observing visibility changes to this element */
_stopObserving: function() {
if (this._observer) {
this._observer.unobserve(this);
if (--this._observer._lazyImgCount <= 0) {
this._deleteObserver(this._observer);
}
this._observer = null;
}
},
/** start observing for this element becoming visible */
_startObserving: function() {
this._getObserver().then(function(observer) {
this._observer = observer;
this._observer.observe(this);
this._observer._lazyImgCount++;
}.bind(this));
},
/** resolve src image relative to original document, not this element */
_resolveSrc: function(testSrc) {
var baseURI = /** @type {string} */(this.ownerDocument.baseURI);
return (new URL(Polymer.ResolveUrl.resolveUrl(testSrc, baseURI), baseURI)).href;
},
/**
* get or create the observer for this element
*
* returns a promise so that IntersectionObserver
* can be polyfilled asynchronously and everything
* be wired up and created before that happens.
*/
_getObserver: function() {
return new Promise(function(resolve, reject) {
polypoly.completes.then(function() {
var observer;
// get element based on selector if there is one
var el = this.observe ? this._getClosest() : null;
var node = el || document.documentElement;
var options = {
root: el,
rootMargin: this.margin,
threshold: this.threshold
}
// See if there is already an observer created for the
// intersection options given. Note we perform a double
// lookup (map within a map) because the actual map key
// is a different instance and there is no hashing
var observersMap = elementObservers.get(node);
if (!observersMap) {
observersMap = new Map();
elementObservers.set(node, observersMap);
}
var key = options.margin + '/' + options.threshold;
observer = observersMap.get(key);
if (!observer) {
// first time for this observer options combination
observer = new IntersectionObserver(notifyEntries, options);
observer._lazyImgKey = key;
observer._lazyImgCount = 0;
observersMap.set(key, observer);
};
resolve(observer);
}.bind(this));
}.bind(this));
},
/** disconnect and delete an observer */
_deleteObserver: function(observer) {
var observersMap = elementObservers.get(observer.root);
if (observersMap) {
observersMap.delete(observer._lazyImgKey);
if (observersMap.size === 0) {
elementObservers.delete(observer.root);
}
}
observer.disconnect();
},
/** get the closest element with the given selector */
_getClosest: function() {
var el = this;
while (el.matches && !el.matches(this.observe)) el = el.parentNode;
return el.matches ? el : null;
}
});
})();
</script>
</dom-module>