-
Notifications
You must be signed in to change notification settings - Fork 224
/
Imager.js
502 lines (409 loc) · 15.8 KB
/
Imager.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
;(function (window, document) {
'use strict';
var addEvent = (function () {
if (document.addEventListener) {
return function addStandardEventListener(el, eventName, fn) {
return el.addEventListener(eventName, fn, false);
};
}
else {
return function addIEEventListener(el, eventName, fn) {
return el.attachEvent('on' + eventName, fn);
};
}
})();
var defaultWidths = [96, 130, 165, 200, 235, 270, 304, 340, 375, 410, 445, 485, 520, 555, 590, 625, 660, 695, 736];
var getKeys = typeof Object.keys === 'function' ? Object.keys : function (object) {
var keys = [],
key;
for (key in object) {
keys.push(key);
}
return keys;
};
var applyEach = function (collection, callbackEach) {
var i = 0,
length = collection.length,
new_collection = [];
for (; i < length; i++) {
new_collection[i] = callbackEach(collection[i], i);
}
return new_collection;
};
var returnFn = function (value) { return value; };
var noop = function () {};
var trueFn = function () { return true; };
var debounce = function (fn, wait) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
fn.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
/*
Construct a new Imager instance, passing an optional configuration object.
Example usage:
{
// Available widths for your images
availableWidths: [Number],
// Selector to be used to locate your div placeholders
selector: '',
// Class name to give your resizable images
className: '',
// If set to true, Imager will update the src attribute of the relevant images
onResize: Boolean,
// Toggle the lazy load functionality on or off
lazyload: Boolean,
// Used alongside the lazyload feature (helps performance by setting a higher delay)
scrollDelay: Number
}
@param {object} configuration settings
@return {object} instance of Imager
*/
var Imager = function (elements, opts) {
var self = this;
var doc = document;
opts = opts || {};
if (elements !== undefined) {
// selector string (not elements)
if (typeof elements === 'string') {
opts.selector = elements;
elements = undefined;
}
// 'opts' object (not elements)
else if (typeof elements.length === 'undefined') {
opts = elements;
elements = undefined;
}
}
this.viewportHeight = doc.documentElement.clientHeight;
this.selector = !elements ? (opts.selector || '.delayed-image-load') : null;
this.className = opts.className || 'image-replace';
this.gif = doc.createElement('img');
this.gif.src = 'data:image/gif;base64,R0lGODlhEAAJAIAAAP///wAAACH5BAEAAAAALAAAAAAQAAkAAAIKhI+py+0Po5yUFQA7';
this.gif.className = this.className;
this.gif.alt = '';
this.lazyloadOffset = opts.lazyloadOffset || 0;
this.scrollDelay = opts.scrollDelay || 250;
this.onResize = opts.hasOwnProperty('onResize') ? opts.onResize : true;
this.lazyload = opts.hasOwnProperty('lazyload') ? opts.lazyload : false;
this.scrolled = false;
this.availablePixelRatios = opts.availablePixelRatios || [1, 2];
this.availableWidths = opts.availableWidths || defaultWidths;
this.onImagesReplaced = opts.onImagesReplaced || noop;
this.widthsMap = {};
this.refreshPixelRatio();
this.widthInterpolator = opts.widthInterpolator || returnFn;
// Needed as IE8 adds a default `width`/`height` attribute…
this.gif.removeAttribute('height');
this.gif.removeAttribute('width');
if (typeof this.availableWidths !== 'function') {
if (typeof this.availableWidths.length === 'number') {
this.widthsMap = Imager.createWidthsMap(this.availableWidths, this.widthInterpolator, this.devicePixelRatio);
}
else {
this.widthsMap = this.availableWidths;
this.availableWidths = getKeys(this.availableWidths);
}
this.availableWidths = this.availableWidths.sort(function (a, b) {
return a - b;
});
}
this.divs = [];
this.add(elements || this.selector);
this.ready(opts.onReady);
setTimeout(function () {
self.init();
}, 0);
};
Imager.prototype.add = function (elementsOrSelector) {
elementsOrSelector = elementsOrSelector || this.selector;
var elements = typeof elementsOrSelector === 'string' ?
document.querySelectorAll(elementsOrSelector) : // Selector
elementsOrSelector; // Elements (NodeList or array of Nodes)
if (elements && elements.length) {
var additional = applyEach(elements, returnFn);
this.changeDivsToEmptyImages(additional);
this.divs = this.divs.concat(additional);
}
};
Imager.prototype.scrollCheck = function () {
var self = this;
var offscreenImageCount = 0;
var elements = [];
if (this.scrolled) {
// collects a subset of not-yet-responsive images and not offscreen anymore
applyEach(this.divs, function (element) {
if (self.isPlaceholder(element)) {
++offscreenImageCount;
if (self.isThisElementOnScreen(element)) {
elements.push(element);
}
}
});
if (offscreenImageCount === 0) {
window.clearInterval(self.interval);
}
this.changeDivsToEmptyImages(elements);
this.scrolled = false;
}
};
Imager.prototype.init = function () {
var self = this;
this.initialized = true;
var filterFn = trueFn;
if (this.lazyload) {
this.registerScrollEvent();
this.scrolled = true;
self.scrollCheck();
filterFn = function (element) {
return self.isPlaceholder(element) === false;
};
}
else {
this.checkImagesNeedReplacing(this.divs);
}
if (this.onResize) {
this.registerResizeEvent(filterFn);
}
this.onReady();
};
/**
* Executes a function when Imager is ready to work
* It acts as a convenient/shortcut for `new Imager({ onReady: fn })`
*
* @since 0.3.1
* @param {Function} fn
*/
Imager.prototype.ready = function (fn) {
this.onReady = fn || noop;
};
Imager.prototype.createGif = function (element) {
// if the element is already a responsive image then we don't replace it again
if (element.className.match(new RegExp('(^| )' + this.className + '( |$)'))) {
return element;
}
var elementClassName = element.getAttribute('data-class');
var elementWidth = element.getAttribute('data-width');
var gif = this.gif.cloneNode(false);
if (elementWidth) {
gif.width = elementWidth;
gif.setAttribute('data-width', elementWidth);
}
gif.className = (elementClassName ? elementClassName + ' ' : '') + this.className;
gif.setAttribute('data-src', element.getAttribute('data-src'));
gif.setAttribute('alt', element.getAttribute('data-alt') || element.alt || this.gif.alt);
element.parentNode.replaceChild(gif, element);
return gif;
};
Imager.prototype.changeDivsToEmptyImages = function (elements) {
var self = this;
applyEach(elements, function (element, i) {
elements[i] = self.createGif(element);
});
if (this.initialized) {
this.checkImagesNeedReplacing(elements);
}
};
/**
* Indicates if an element is an Imager placeholder
*
* @since 1.3.1
* @param {HTMLImageElement} element
* @returns {boolean}
*/
Imager.prototype.isPlaceholder = function (element) {
return element.src === this.gif.src;
};
/**
* Returns true if an element is located within a screen offset.
*
* @param {HTMLElement} element
* @returns {boolean}
*/
Imager.prototype.isThisElementOnScreen = function (element) {
// document.body.scrollTop was working in Chrome but didn't work on Firefox, so had to resort to window.pageYOffset
// but can't fallback to document.body.scrollTop as that doesn't work in IE with a doctype (?) so have to use document.documentElement.scrollTop
var elementOffsetTop = 0;
var offset = Imager.getPageOffset() + this.lazyloadOffset;
if (element.offsetParent) {
do {
elementOffsetTop += element.offsetTop;
}
while (element = element.offsetParent);
}
return elementOffsetTop < (this.viewportHeight + offset);
};
Imager.prototype.checkImagesNeedReplacing = function (images, filterFn) {
var self = this;
filterFn = filterFn || trueFn;
if (!this.isResizing) {
this.isResizing = true;
this.refreshPixelRatio();
applyEach(images, function (image) {
if (filterFn(image)) {
self.replaceImagesBasedOnScreenDimensions(image);
}
});
this.isResizing = false;
this.onImagesReplaced(images);
}
};
/**
* Upgrades an image from an empty placeholder to a fully sourced image element
*
* @param {HTMLImageElement} image
*/
Imager.prototype.replaceImagesBasedOnScreenDimensions = function (image) {
var computedWidth, naturalWidth;
naturalWidth = Imager.getNaturalWidth(image);
computedWidth = typeof this.availableWidths === 'function' ? this.availableWidths(image)
: this.determineAppropriateResolution(image);
image.width = computedWidth;
if (!this.isPlaceholder(image) && computedWidth <= naturalWidth) {
return;
}
image.src = this.changeImageSrcToUseNewImageDimensions(image.getAttribute('data-src'), computedWidth);
image.removeAttribute('width');
image.removeAttribute('height');
};
Imager.prototype.determineAppropriateResolution = function (image) {
return Imager.getClosestValue(image.getAttribute('data-width') || image.parentNode.clientWidth, this.availableWidths);
};
/**
* Updates the device pixel ratio value used by Imager
*
* It is performed before each replacement loop, in case a user zoomed in/out
* and thus updated the `window.devicePixelRatio` value.
*
* @api
* @since 1.0.1
*/
Imager.prototype.refreshPixelRatio = function refreshPixelRatio() {
this.devicePixelRatio = Imager.getClosestValue(Imager.getPixelRatio(), this.availablePixelRatios);
};
Imager.prototype.changeImageSrcToUseNewImageDimensions = function (src, selectedWidth) {
return src
.replace(/{width}/g, Imager.transforms.width(selectedWidth, this.widthsMap))
.replace(/{pixel_ratio}/g, Imager.transforms.pixelRatio(this.devicePixelRatio));
};
Imager.getPixelRatio = function getPixelRatio(context) {
return (context || window)['devicePixelRatio'] || 1;
};
Imager.createWidthsMap = function createWidthsMap (widths, interpolator, pixelRatio) {
var map = {},
i = widths.length;
while (i--) {
map[widths[i]] = interpolator(widths[i], pixelRatio);
}
return map;
};
Imager.transforms = {
pixelRatio: function (value) {
return value === 1 ? '' : '-' + value + 'x';
},
width: function (width, map) {
return map[width] || width;
}
};
/**
* Returns the closest upper value.
*
* ```js
* var candidates = [1, 1.5, 2];
*
* Imager.getClosestValue(0.8, candidates); // -> 1
* Imager.getClosestValue(1, candidates); // -> 1
* Imager.getClosestValue(1.3, candidates); // -> 1.5
* Imager.getClosestValue(3, candidates); // -> 2
* ```
*
* @api
* @since 1.0.1
* @param {Number} baseValue
* @param {Array.<Number>} candidates
* @returns {Number}
*/
Imager.getClosestValue = function getClosestValue(baseValue, candidates) {
var i = candidates.length,
selectedWidth = candidates[i - 1];
baseValue = parseFloat(baseValue);
while (i--) {
if (baseValue <= candidates[i]) {
selectedWidth = candidates[i];
}
}
return selectedWidth;
};
Imager.prototype.registerResizeEvent = function (filterFn) {
var self = this;
addEvent(window, 'resize', debounce(function () {
self.checkImagesNeedReplacing(self.divs, filterFn);
}, 100));
};
Imager.prototype.registerScrollEvent = function () {
var self = this;
this.scrolled = false;
this.interval = window.setInterval(function () {
self.scrollCheck();
}, self.scrollDelay);
addEvent(window, 'scroll', function () {
self.scrolled = true;
});
addEvent(window, 'resize', function () {
self.viewportHeight = document.documentElement.clientHeight;
self.scrolled = true;
});
};
Imager.getPageOffsetGenerator = function getPageVerticalOffset(testCase) {
if (testCase) {
return function () { return window.pageYOffset; };
}
else {
return function () { return document.documentElement.scrollTop; };
}
};
/**
* Returns the naturalWidth of an image element.
*
* @since 1.3.1
* @param {HTMLImageElement} image
* @return {Number} Image width in pixels
*/
Imager.getNaturalWidth = (function () {
if ('naturalWidth' in (new Image())) {
return function (image) {
return image.naturalWidth;
};
}
// non-HTML5 browsers workaround
return function (image) {
var imageCopy = document.createElement('img');
imageCopy.src = image.src;
return imageCopy.width;
};
})();
// This form is used because it seems impossible to stub `window.pageYOffset`
Imager.getPageOffset = Imager.getPageOffsetGenerator(Object.prototype.hasOwnProperty.call(window, 'pageYOffset'));
// Exporting for testing and convenience purpose
Imager.applyEach = applyEach;
Imager.addEvent = addEvent;
Imager.debounce = debounce;
/* jshint ignore:start */
if (typeof module === 'object' && typeof module.exports === 'object') {
// CommonJS, just export
module.exports = exports = Imager;
} else if (typeof define === 'function' && define.amd) {
// AMD support
define(function () { return Imager; });
} else if (typeof window === 'object') {
// If no AMD and we are in the browser, attach to window
window.Imager = Imager;
}
/* jshint ignore:end */
}(window, document));