-
Notifications
You must be signed in to change notification settings - Fork 0
/
lazyblur.js
executable file
·265 lines (219 loc) · 8.73 KB
/
lazyblur.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
/*! Image Zoom - v1
* Copyright (c) 2016 Mattias Hinderson
* License: MIT
*/
(function (window, factory) {
'use strict';
if (typeof define == 'function' && define.amd) {
// AMD
define([
'./utils',
'./pubsub',
'./vendor/stackblur',
'./vendor/picturefill'
], function(utils, pubsub, stackblur, picturefill) {
return factory(window, utils, pubsub, stackblur, picturefill);
});
} else if (typeof exports == 'object') {
// CommonJS
module.exports = factory(
window,
require('./utils'),
require('./pubsub'),
require('./vendor/stackblur'),
require('./vendor/picturefill')
);
}
}(window, function factory (window, utils, pubsub, stackblur, picturefill) {
'use strict';
// Constants
var BLUR_AMOUNT = 40;
// Unloaded items
var unloadedItems = [];
// Support helpers
var supportsObjectFit = 'objectFit' in document.documentElement.style;
var supportsIntersectionObserver = 'IntersectionObserver' in window;
// Add a background-image fallback for object-fit
// Must be called after Picturefill
function polyfillObjectFit (img, container) {
if (supportsObjectFit) { return; }
utils.requestAnimFrame.call(window, function ( ) {
// Get current image src: Edge only supports 'currentSrc' for getting the current image src ('src' returns value DOM value)
var imageSrc = img.currentSrc || img.src;
img.style.display = 'none';
container.style.backgroundSize = img.getAttribute('data-object-fit');
container.style.backgroundImage = 'url(' + imageSrc + ')';
});
}
function checkImageVisibility ( ) {
if (supportsIntersectionObserver) return;
if (!Object.keys(unloadedItems).length) {
// We've loaded all images in the document
return destroy();
}
utils.forEach(unloadedItems, function (index, item) {
if (!item) { return; }
if (utils.isInViewport(item)) {
loadMedia(item);
}
});
}
function loadMedia (item) {
// Remove item from unloaded items array
delete unloadedItems[unloadedItems.indexOf(item)];
var showMedia = function ( ) {
var mediaElem = this;
item.classList.remove('loading-media');
item.classList.add('media-loaded');
pubsub.publish('mediaLoaded', [item, mediaElem]);
};
var makeImageElem = function (attributes) {
var mediaElem = new Image();
mediaElem.classList.add('media');
var constructAttributes = function (prop) {
mediaElem.setAttribute(prop, attributes[prop]);
};
item.appendChild(mediaElem);
// Does the browser support srcset?
// We either have srcset and native support for it, or just a regular src attribute
if ('srcset' in mediaElem || !attributes.hasOwnProperty('srcset')) {
mediaElem.onload = showMedia.bind(mediaElem);
Object.keys(attributes).forEach(constructAttributes);
} else {
// We have only srcset, and we need to polyfill
Object.keys(attributes).forEach(constructAttributes);
showMedia.call(mediaElem);
picturefill({ elements: [ mediaElem ] }); // Polyfill srcset images
if (attributes.hasOwnProperty('data-object-fit')) {
polyfillObjectFit(mediaElem, item); // Polyfill object-fit images
}
}
return mediaElem;
};
var makeVideoElem = function (attributes) {
var video = document.createElement('video');
video.className = 'media';
video.autoplay = true;
// Construct attributes
Object.keys(attributes).forEach(function (prop) {
video.setAttribute(prop, attributes[prop]);
});
return video;
};
var fallbackVideoElem = function ( ) {
// Device doesn't support autoplay
// Delete video attributes
delete attributes.loop;
delete attributes.muted;
delete attributes.autoplay;
delete attributes['webkit-playsinline'];
// Append video fallback image
attributes.src = item.getAttribute('data-video-fallback');
var mediaElem = makeImageElem(attributes);
item.classList.add('using-video-fallback');
mediaElem.classList.add('video-fallback');
};
var attributes = JSON.parse(item.getAttribute('data-attributes'));
var type = (attributes.src || attributes.srcset.split(',')[0].split(' ')[0]).match(/\.(jpg|jpeg|png|gif)$/) ? 'image' : 'video';
// Add loading class
item.classList.add('loading-media');
// Try to load media element
if (type === 'video') {
var video = makeVideoElem(attributes);
video.muted = true;
var videoPromise = video.play();
if (videoPromise !== undefined) {
videoPromise.then(function () {
item.appendChild(video);
showMedia.call(video);
}).catch(fallbackVideoElem);
} else {
fallbackVideoElem();
}
} else {
makeImageElem(attributes);
}
}
function createBlurryPlaceholder (item) {
var placeholder = item.getElementsByTagName('img')[0];
var canvas = item.getElementsByTagName('canvas')[0];
// Force reload
var placeholderImg = new Image();
placeholderImg.crossOrigin = 'Anonymous';
placeholderImg.src = placeholder.src;
// Wait for thumb to load completely
var applyBlur = function ( ) {
canvas.getContext('2d').drawImage(placeholderImg, 0, 0, canvas.width, canvas.height);
stackblur.canvasRGB(canvas, 0, 0, canvas.width, canvas.height, BLUR_AMOUNT);
item.classList.add('placeholder-loaded');
pubsub.publish('placeholderCreated', item);
};
if (placeholderImg.complete) {
applyBlur();
} else {
placeholderImg.onload = applyBlur;
}
return item;
}
function destroy ( ) {
window.removeEventListener('resize', resizeEvent);
window.removeEventListener('scroll', scrollEvent);
}
var lazyBlur = function (query, options) {
if (!query) return;
if (options) {
BLUR_AMOUNT = options.blur;
}
// Export event emitter
this.on = pubsub.subscribe;
// Export functions
this.check = checkImageVisibility;
// Instantiate all provided queries
var elems = (typeof query === 'string' ? document.querySelectorAll(query) : query);
utils.forEach(elems, function (index, elem) {
var unloadedItem = createBlurryPlaceholder(elem);
unloadedItems.push(unloadedItem);
});
// Check for viewport visibility
if (supportsIntersectionObserver) {
var config = {
root: null,
rootMargin: '0px',
threshold: options['threshold'] || 0.05
};
var observer = new IntersectionObserver(function (changes, observer) {
changes.forEach(function (change) {
if (change.intersectionRatio > 0) {
// Stop watching and load the image
observer.unobserve(change.target);
loadMedia(change.target);
}
});
}, config);
if (Object.keys(unloadedItems).length) {
utils.forEach(unloadedItems, function (index, item) {
if (item) {
observer.observe(item);
}
});
} else {
observer.disconnect();
destroy();
}
} else {
// Do an initial check of image visibility
checkImageVisibility();
// Fallback to event listeners when Intersection Observers isn't supported
window.addEventListener('resize', checkImageVisibility);
window.addEventListener('scroll', checkImageVisibility);
}
};
// Expose to interface
if (typeof module === 'object' && typeof module.exports === 'object') {
// CommonJS, just export
module.exports = lazyBlur;
} else if (typeof define === 'function' && define.amd) {
// AMD support
define('lazyBlur', function ( ) { return lazyBlur; } );
}
}));