-
Notifications
You must be signed in to change notification settings - Fork 1
/
smartImages.js
381 lines (325 loc) · 11.8 KB
/
smartImages.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
/**
* SmartImages
* ===========
* SmartImages provides multiple functions:
*
* - Loading retina images when necessary and/or possible
* - Making image sources responsive by swapping image sources on a predefined breakpoint.
* - Adding lazy loading to images to only load when they come near the viewport.
* - Added option to pre-define the future image sizes so the layout will be preserved for lazy images.
* - Implemented functionality for background images of containers.
* - Implemented functionality of custom query and source
* - Implemented application on any DOM node (i.e. iframes)
*
* @url: https://github.com/Paratron/smartimages
* @author: Christian Engel <[email protected]>
* @version: 2.5.1 (28.02.2017)
*/
(function () {
'use strict';
var isRetina,
isMobile,
initDone = false,
smartImages,
scrollTimeout,
autoInit = true,
scrollListening = false,
hasLazyImages = false,
hasLazyContainers = false,
customQueries = {};
isRetina = window.matchMedia('(-webkit-min-device-pixel-ratio: 1.25),(min-resolution: 120dpi)').matches;
window['smartImages'] = smartImages = window['smartImages'] || {};
smartImages.mediaQuery = smartImages.mediaQuery || '(max-width: 650px)';
function responsiveHandler(e) {
isMobile = e.matches;
var scrollTop, lazyBorder;
scrollTop = document.body.scrollTop;
lazyBorder = scrollTop + (window.innerHeight * 1.5);
processImages(scrollTop, lazyBorder);
processContainers(scrollTop, lazyBorder);
}
/**
* Attached to custom queries.
* @param elm
*/
function customResponsiveHandler(elm) {
var scrollTop, lazyBorder;
scrollTop = document.body.scrollTop;
lazyBorder = scrollTop + (window.innerHeight * 1.5);
if (elm.nodeName === 'IMG') {
assignImg(elm, scrollTop, lazyBorder, false, false);
return;
}
assignContainer(elm, scrollTop, lazyBorder, false, false);
}
/**
* This detects the currently correct src / background of the given element and returns it.
* @param elm
* @param scrollTop
* @param lazyBorder
* @param justSrc
* @returns {*}
*/
function getSrc(elm, scrollTop, lazyBorder, justSrc) {
var o = {
src1x: elm.getAttribute('data-src'),
src2x: elm.getAttribute('data-src-2x'),
src1x_mobile: elm.getAttribute('data-src-mobile'),
src2x_mobile: elm.getAttribute('data-src-mobile-2x'),
size1x: elm.getAttribute('data-size'),
size2x: elm.getAttribute('data-size-2x'),
size1x_mobile: elm.getAttribute('data-size-mobile'),
size2x_mobile: elm.getAttribute('data-size-mobile-2x'),
custom: elm.getAttribute('data-src-custom'),
customQuery: elm.getAttribute('data-match-custom-id'),
customSize: elm.getAttribute('data-size-custom'),
lazy: elm.getAttribute('data-lazy') !== null
};
if (o.size1x) {
o.size1x = o.size1x.split('x');
}
if (o.size2x) {
o.size2x = o.size2x.split('x');
}
if (o.size1x_mobile) {
o.size1x_mobile = o.size1x_mobile.split('x');
}
if (o.size2x_mobile) {
o.size2x_mobile = o.size2x_mobile.split('x');
}
var src = o.src1x,
size = o.size1x;
if (isMobile) {
if (o.src1x_mobile !== null) {
src = o.src1x_mobile;
size = o.size1x_mobile;
}
if (isRetina) {
if (o.src2x_mobile !== null) {
src = o.src2x_mobile;
size = o.size2x_mobile;
} else {
if (o.src2x !== null) {
src = o.src2x;
size = o.size2x;
}
}
}
} else {
if (isRetina && o.src2x !== null) {
src = o.src2x;
size = o.size2x;
}
}
if (o.custom && o.customQuery) {
if (customQueries[o.customQuery] && customQueries[o.customQuery].matches) {
src = o.custom;
size = o.customSize;
}
}
if (o.lazy) {
if (elm.tagName.toUpperCase() === 'IMG') {
hasLazyImages = true;
} else {
hasLazyContainers = true;
}
if (scrollTop + elm.getBoundingClientRect().top > lazyBorder) {
if (size && !elm.getAttribute('data-dummy')) {
elm.setAttribute('data-dummy', '1');
return getDummy(size);
}
return null;
}
}
if (justSrc) {
return src || '';
}
if (src === null) {
return null;
}
return src;
}
/**
* This finds and applies the currently correct background of an container.
* @param elm
* @param scrollTop
* @param lazyBorder
* @param force
* @param justSrc
*/
function assignContainer(elm, scrollTop, lazyBorder, force, justSrc) {
if (elm.getAttribute('data-smart-ignore') !== null && !force) {
return;
}
var src = getSrc(elm, scrollTop, lazyBorder, justSrc);
if (src !== null) {
elm.style.backgroundImage = src.substr(0, 4) === 'url(' ? src : 'url(' + src + ')';
}
}
/**
* This finds and applies the currently correct src of an image element.
* @param img
* @param scrollTop
* @param lazyBorder
* @param force
* @param justSrc
*/
function assignImg(img, scrollTop, lazyBorder, force, justSrc) {
if (img.getAttribute('data-smart-ignore') !== null && !force) {
return;
}
var src = getSrc(img, scrollTop, lazyBorder, justSrc);
if (src !== null && img.src !== src) {
img.src = src;
}
}
/**
* This method creates a transparent dummy image with the given dimensions and
* returns the result as data URL.
* @type {Element}
*/
var dummyCvs = document.createElement('canvas');
function getDummy(size) {
dummyCvs.width = size[0];
dummyCvs.height = size[1];
return dummyCvs.toDataURL();
}
/**
* This loops over all images in the document and enables their smart functionality.
* This is being called from within the init() method.
* @param scrollTop
* @param lazyBorder
*/
function processImages(scrollTop, lazyBorder) {
var img, imgId, entities;
if(document.querySelectorAll){
entities = Array.prototype.concat(
Array.prototype.slice.call(document.images),
Array.prototype.slice.call(document.querySelectorAll('[data-smartEntity]')));
} else {
entities = document.images;
}
for (var i = 0; i < entities.length; i++) {
img = entities[i];
if (img.getAttribute('data-match-custom') && !img.getAttribute('data-match-custom-id')) {
imgId = Math.random().toString().split('.')[1];
img.setAttribute('data-match-custom-id', imgId);
customQueries[imgId] = window.matchMedia(img.getAttribute('data-match-custom'));
customQueries[imgId].addListener((function (img) {
return function(){
customResponsiveHandler(img);
};
})(img));
}
assignImg(img, scrollTop, lazyBorder, false, false);
}
if (hasLazyImages && !scrollListening) {
scrollListening = true;
window.addEventListener('scroll', observeLazy);
}
}
/**
* This selects any container with the "data-smartImageContainer" attribute and enables
* smart background functionality on them.
* This is being called from within the init() method.
* @param scrollTop
* @param lazyBorder
*/
function processContainers(scrollTop, lazyBorder) {
var elm;
var elms = document.querySelectorAll('[data-smartImageContainer]');
for (var i = 0; i < elms.length; i++) {
elm = elms[i];
if (elm.getAttribute('data-match-custom') && !elm.getAttribute('data-match-custom-id')) {
var imgId = Math.random().toString().split('.')[1];
elm.setAttribute('data-match-custom-id', imgId);
customQueries[imgId] = window.matchMedia(elm.getAttribute('data-match-custom'));
customQueries[imgId].addListener(function () {
customResponsiveHandler(elm);
});
}
assignContainer(elm, scrollTop, lazyBorder, false, false);
}
if (hasLazyContainers && !scrollListening) {
scrollListening = true;
window.addEventListener('scroll', observeLazy);
}
}
function observeLazy() {
if(scrollTimeout){
return;
}
scrollTimeout = true;
setTimeout(function () {
scrollTimeout = false;
var scrollTop = document.body.scrollTop,
lazyBorder = scrollTop + (window.innerHeight * 1.5);
if (hasLazyImages) {
processImages(scrollTop, lazyBorder);
}
if (hasLazyContainers) {
processContainers(scrollTop, lazyBorder);
}
}, 100);
}
/**
* This processes all images and containers on the page for the first time and also sets up
* the event listener for the media query to react on scaling.
*/
smartImages['init'] = function () {
var scrollTop, lazyBorder;
if (initDone) {
return;
}
initDone = true;
scrollTop = document.body.scrollTop;
lazyBorder = scrollTop + (window.innerHeight * 1.5);
processImages(scrollTop, lazyBorder);
if (document.querySelectorAll) {
processContainers(scrollTop, lazyBorder);
}
//React on the mobile media query and attach event listeners.
var responsiveQuery = window.matchMedia(smartImages.mediaQuery);
responsiveHandler(responsiveQuery);
responsiveQuery.addListener(responsiveHandler);
console.log('Images are smart, now.');
};
/**
* Prevent the automatic initialization and replacement of all image sources in the document.
*/
smartImages['noAutoInit'] = function () {
autoInit = false;
};
/**
* Manually perform the assignation of the smart image source ONCE on the given element.
* @param elm
*/
smartImages['manualAssign'] = function (elm) {
if (elm instanceof Image || elm.nodeName === 'IMG') {
assignImg(elm, document.body.scrollTop, (document.body.scrollTop + (window.innerHeight * 1.5)), true, false);
} else {
assignContainer(elm, document.body.scrollTop, (document.body.scrollTop + (window.innerHeight * 1.5)), true, false);
}
};
/**
* Just get the the source that would currently apply for an image without setting it.
* @param elm
* @returns string
*/
smartImages['getSrc'] = function (elm) {
return assignImg(elm, 0, 0, true, true);
};
/**
* Just get the background that would currently apply for a container without setting it.
* @param elm
* @returns string
*/
smartImages['getBackground'] = function (elm) {
return assignContainer(elm, 0, 0, true, true);
};
window.addEventListener('load', function () {
if (autoInit === true) {
smartImages['init']();
}
});
})();