forked from bbc/Imager.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Imager.js
320 lines (247 loc) · 9.78 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
;(function (window, document) {
'use strict';
var defaultWidths, getKeys, isArray, nextTick;
nextTick = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
function applyEach (collection, callbackEach) {
var i = 0,
length = collection.length,
new_collection = [];
for (; i < length; i++) {
new_collection[i] = callbackEach(collection[i]);
}
return new_collection;
}
function returnDirectValue (value) {
return value;
}
defaultWidths = [96, 130, 165, 200, 235, 270, 304, 340, 375, 410, 445, 485, 520, 555, 590, 625, 660, 695, 736];
getKeys = typeof Object.keys === 'function' ? Object.keys : function (object) {
var keys = [],
key;
for (key in object) {
keys.push(key);
}
return keys;
};
isArray = function isArray (object) {
return Object.prototype.toString.call(object) === '[object Array]';
};
/*
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
*/
function Imager (elements, opts) {
var self = this,
doc = document;
opts = opts || {};
if (elements !== undefined) {
// selector
if (typeof elements === 'string') {
opts.selector = elements;
elements = undefined;
}
// config object
else if (!elements.hasOwnProperty('length')) {
opts = elements;
elements = undefined;
}
}
this.imagesOffScreen = [];
this.viewportHeight = doc.documentElement.clientHeight;
this.selector = opts.selector || '.delayed-image-load';
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.scrollDelay = opts.scrollDelay || 250;
this.onResize = opts.hasOwnProperty('onResize') ? opts.onResize : true;
this.lazyload = opts.hasOwnProperty('lazyload') ? opts.lazyload : false;
this.scrolled = false;
this.devicePixelRatio = Imager.getPixelRatio();
if (opts.availableWidths === undefined) {
opts.availableWidths = defaultWidths;
}
if (isArray(opts.availableWidths)) {
this.availableWidths = opts.availableWidths;
this.widthsMap = Imager.createWidthsMap(this.availableWidths);
}
else {
this.availableWidths = getKeys(opts.availableWidths);
this.widthsMap = opts.availableWidths;
}
this.availableWidths = this.availableWidths.sort(function (a, b) {
return a - b;
});
if (elements) {
this.divs = applyEach(elements, returnDirectValue);
this.selector = null;
}
else {
this.divs = applyEach(doc.querySelectorAll(this.selector), returnDirectValue);
}
this.changeDivsToEmptyImages();
nextTick(function(){
self.init();
});
}
Imager.prototype.scrollCheck = function(){
if (this.scrolled) {
if (!this.imagesOffScreen.length) {
window.clearInterval(this.interval);
}
this.divs = this.imagesOffScreen.slice(0); // copy by value, don't copy by reference
this.imagesOffScreen.length = 0;
this.changeDivsToEmptyImages();
this.scrolled = false;
}
};
Imager.prototype.init = function(){
this.initialized = true;
this.checkImagesNeedReplacing(this.divs);
if (this.onResize) {
this.registerResizeEvent();
}
if (this.lazyload) {
this.registerScrollEvent();
}
};
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 gif = this.gif.cloneNode(false);
gif.width = element.getAttribute('data-width');
gif.setAttribute('data-src', element.getAttribute('data-src'));
element.parentNode.replaceChild(gif, element);
return gif;
};
Imager.prototype.changeDivsToEmptyImages = function(){
var divs = this.divs,
i = divs.length,
element;
while (i--) {
element = divs[i];
if (this.lazyload) {
if (this.isThisElementOnScreen(element)) {
this.divs[i] = this.createGif(element);
} else {
this.imagesOffScreen.push(element);
}
} else {
this.divs[i] = this.createGif(element);
}
}
if (this.initialized) {
this.checkImagesNeedReplacing(this.divs);
}
};
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 offset = (window.hasOwnProperty('pageYOffset')) ? window.pageYOffset : document.documentElement.scrollTop;
return (element.offsetTop < (this.viewportHeight + offset)) ? true : false;
};
Imager.prototype.checkImagesNeedReplacing = function (images) {
var i = images.length;
if (!this.isResizing) {
this.isResizing = true;
while (i--) {
this.replaceImagesBasedOnScreenDimensions(images[i]);
}
this.isResizing = false;
}
};
Imager.prototype.replaceImagesBasedOnScreenDimensions = function (image) {
var computedWidth, src;
computedWidth = typeof this.availableWidths === 'function' ? this.availableWidths(image)
: this.determineAppropriateResolution(image);
src = this.changeImageSrcToUseNewImageDimensions(image.getAttribute('data-src'), computedWidth);
image.src = src;
};
Imager.prototype.determineAppropriateResolution = function (image) {
var imagewidth = image.clientWidth,
i = this.availableWidths.length,
selectedWidth = this.availableWidths[i - 1];
while (i--) {
if (imagewidth <= this.availableWidths[i]) {
selectedWidth = this.availableWidths[i];
}
}
return selectedWidth;
};
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(){
return window.devicePixelRatio || 1;
};
Imager.createWidthsMap = function createWidthsMap (widths) {
var map = {},
i = widths.length;
while (i--) {
map[widths[i]] = null;
}
return map;
};
Imager.transforms = {
pixelRatio: function (value) {
return value === 1 ? '' : '-' + value + 'x';
},
width: function (width, map) {
return map[width] || width;
}
};
Imager.prototype.registerResizeEvent = function(){
var self = this;
window.addEventListener('resize', function(){
self.checkImagesNeedReplacing(self.divs);
}, false);
};
Imager.prototype.registerScrollEvent = function (){
var self = this;
this.scrolled = false;
this.interval = window.setInterval(function(){
self.scrollCheck();
}, self.scrollDelay);
window.addEventListener('scroll', function(){
self.scrolled = true;
}, false);
};
/* global module, exports: true, define */
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;
}
/* global -module, -exports, -define */
}(window, document));