forked from tubalmartin/riloadr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathriloadr.js
723 lines (597 loc) · 24.5 KB
/
riloadr.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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
/*!
* Riloadr.js 1.2.0 (c) 2012 Tubal Martin - MIT license
*/
!function(definition) {
if (typeof define === 'function' && define.amd) {
// Register as an AMD module.
define(definition);
} else {
// Browser globals
window.Riloadr = definition();
}
}(function(){
'use strict';
var ON = 'on'
, TRUE = !0
, FALSE = !1
, DELAY = 250
, NULL = null
, LOAD = 'load'
, CALL = 'call'
, APPLY = 'apply'
, ERROR = 'error'
, EMPTYSTRING = ''
, LENGTH = 'length'
, SCROLL = 'scroll'
, RESIZE = 'resize'
, ONLOAD = ON+LOAD
, ONERROR = ON+ERROR
, RETRIES = 'retries'
, COMPLETE = 'complete'
, RILOADED = 'riloaded'
, CLASSNAME = 'className'
, PROTOTYPE = 'prototype'
, CLIENTTOP = 'clientTop'
, ONCOMPLETE = ON+COMPLETE
, LOADIMAGES = 'loadImages'
, READYSTATE = 'readyState'
, ORIENTATION = 'orientation'
, ATTACHEVENT = 'attachEvent'
, CLIENTHEIGHT = 'clientHeight'
, EVENTLISTENER = 'EventListener'
, READYSTATECHANGE = 'readystatechange'
, QUERYSELECTORALL = 'querySelectorAll'
, ADDEVENTLISTENER = 'add'+EVENTLISTENER
, ORIENTATIONCHANGE = ORIENTATION+'change'
, GETBOUNDINGCLIENTRECT = 'getBoundingClientRect'
, body
, win = window
, doc = win.document
, docElm = doc.documentElement
// Event model
, w3c = ADDEVENTLISTENER in doc
, pre = w3c ? EMPTYSTRING : ON
, add = w3c ? ADDEVENTLISTENER : ATTACHEVENT
, rem = w3c ? 'remove'+EVENTLISTENER : 'detachEvent'
// REGEXPS
, QUESTION_MARK_REGEX = /\?/
, BREAKPOINT_NAME_REGEX = /{breakpoint-name}/gi
// Feature support
, selectorsApiSupported = QUERYSELECTORALL in doc
, belowfoldSupported = GETBOUNDINGCLIENTRECT in docElm
, orientationSupported = ORIENTATION in win && ON+ORIENTATIONCHANGE in win
// Screen info
, viewportWidth
, screenWidth = win.screen.width
, devicePixelRatio = win.devicePixelRatio || 1
// Bandwidth info (bool)
, hasLowBandwidth = hasLowBandwidth()
// Support for Opera Mini (executes Js on the server)
, operaMini = Object[PROTOTYPE].toString[CALL](win.operamini) === '[object OperaMini]'
// Other uninitialized vars
, onDomReady, lastOrientation;
// Remove "no-js" class from <html> element, if it exists:
docElm[CLASSNAME] = docElm[CLASSNAME].replace(/(^|\s)no-js(\s|$)/, '$1$2');
/*
* Constructor: Riloadr
* Creates a Riloadr object
* Parameters:
* options - Object containing configuration options
*/
function Riloadr(options) {
// PRIVATE PROPERTIES
// ------------------
var instance = this
// Base path
, base = options.base || EMPTYSTRING
// CSS-like breakpoints configuration (required)
, breakpoints = options.breakpoints || error('"breakpoints" not defined.')
// Group name: a name to identify images that must be processed by Riloadr.
// Specified in the 'class' attribute of 'img' tags.
, className = options.name || 'responsive'
, classNameRegexp = new RegExp('(^|\\s)'+className+'(\\s|$)')
// Defer load: disabled by default, if enabled falls back to "load".
// Possible values: 'belowfold' & 'load'.
, deferMode = options.defer && (options.defer).toLowerCase() || FALSE
// Setting foldDistance to n causes image to load n pixels before it is visible.
// Falls back to 100px
, foldDistance = options.foldDistance || 100
// Set to true to deliver Hi-Res images despite connection speed.
// Defaults to false, meaning connection speed is not ignored so
// Hi-Res images will only be requested if connection speed is fast enough.
, ignoreLowBandwidth = options.ignoreLowBandwidth || FALSE
// # of times to retry to load an image if initial loading failed.
// Falls back to 0 (no retries)
, retries = options[RETRIES] || 0
// Id of a DOM node where Riloadr must look for 'responsive' images.
// Falls back to body if not set.
, root = options.root || NULL
// 'belowfold' defer mode?
, belowfoldEnabled = deferMode === 'belowfold' && belowfoldSupported && !operaMini
// Reduce by 5.5x the # of times loadImages is called when scrolling
, scrollListener = belowfoldEnabled && throttle(function() {
instance[LOADIMAGES]();
}, DELAY)
// Reduce to 1 the # of times loadImages is called when resizing
, resizeListener = belowfoldEnabled && debounce(function() {
instance[LOADIMAGES]();
}, DELAY)
// Reduce to 1 the # of times loadImages is called when orientation changes.
, orientationchangeListener = belowfoldEnabled && debounce(function(){
if (win[ORIENTATION] !== lastOrientation) {
lastOrientation = win[ORIENTATION];
instance[LOADIMAGES]();
}
}, DELAY)
// Static list (array) of images.
, images = []
// # of images not completely loaded
, imagesPendingLoad = 0
// Size of images to use.
, imgSize;
// PRIVATE METHODS
// ---------------
/*
* Adds event listeners if defer mode is 'belowfold'
* React on scroll, resize and orientationchange events
*/
function addBelowfoldListeners() {
addEvent(win, SCROLL, scrollListener);
addEvent(win, RESIZE, resizeListener);
// Is orientationchange event supported? If so, let's try to avoid false
// positives by checking if win.orientation has actually changed.
if (orientationSupported) {
lastOrientation = win[ORIENTATION];
addEvent(win, ORIENTATIONCHANGE, orientationchangeListener);
}
}
/*
* Removes event listeners if defer mode is 'belowfold'
*/
function removeBelowfoldListeners() {
removeEvent(win, SCROLL, scrollListener);
removeEvent(win, RESIZE, resizeListener);
// Is orientationchange event supported? If so, remove the listener
orientationSupported && removeEvent(win, ORIENTATIONCHANGE, orientationchangeListener);
}
/*
* Loads an image.
*/
function loadImage(img, idx) {
// Initial # of times we tried to reload this image
img[RETRIES] = 0;
// Image callbacks
img[ONLOAD] = imageOnloadCallback;
img[ONERROR] = imageOnerrorCallback;
// Load it
img.src = getImageSrc(img, base, imgSize);
// Reduce the images array for shorter loops
images.splice(idx, 1);
}
/*
* Image onload Callback
*/
function imageOnloadCallback() {
var img = this;
img[ONLOAD] = img[ONERROR] = NULL;
img[CLASSNAME] = img[CLASSNAME].replace(classNameRegexp, '$1$2');
ONLOAD in options && options[ONLOAD][CALL](img);
onCompleteCallback();
}
/*
* Image onerror Callback
* If user sets 'retries' > 0, Riloadr will try to load an image n times
* if an image fails to load.
*/
function imageOnerrorCallback() {
var img = this;
ONERROR in options && options[ONERROR][CALL](img);
if (img[RETRIES] < retries) {
img[RETRIES]++;
img.src = getImageSrc(img, base, imgSize, TRUE);
} else {
// If an image fails to load consider it loaded.
onCompleteCallback();
}
}
/*
* oncomplete Callback
* Executes when all images in a group are 100% (down)loaded.
*/
function onCompleteCallback() {
imagesPendingLoad--;
imagesPendingLoad == 0 && ONCOMPLETE in options && options[ONCOMPLETE]();
}
// PUBLIC PRIVILEGED METHODS
// -------------------------
/*
* Collects and loads all 'responsive' images from the DOM node specified.
* If no DOM node is specified, it falls back to body.
* Notes:
* - Friendly with other scripts running.
* - Must be publicly accesible but should not be called directly.
*/
instance[LOADIMAGES] = function(update) {
// Schedule it to run after the current call stack has cleared.
defer(function(imageList, current, i){
// If initial collection is not done or
// new images have been added to the DOM, collect them.
if (!images[LENGTH] || update === TRUE) {
// Add event listeners
belowfoldEnabled && addBelowfoldListeners();
imageList = selectorsApiSupported &&
root[QUERYSELECTORALL]('img.'+className) ||
root.getElementsByTagName('img');
// Create a static list
i = 0;
while (current = imageList[i]) {
// If we haven't processed this image yet and it is a responsive image
if (current && !current[RILOADED] &&
(selectorsApiSupported ||
current[CLASSNAME].indexOf(className) >= 0)) {
// Flag to avoid reprocessing
current[RILOADED] = TRUE;
// Add image to the list
images.push(current);
// Increment counter
imagesPendingLoad++;
}
i++;
}
}
// Load images
if (images[LENGTH]) {
i = 0;
while (current = images[i]) {
if (current &&
(!belowfoldEnabled || belowfoldEnabled &&
!isBelowTheFold(current, foldDistance))) {
loadImage(current, i);
i--;
}
i++;
}
}
// No more images to load? remove event listeners
belowfoldEnabled && !images[LENGTH] && removeBelowfoldListeners();
// Clean up
imageList = current = NULL;
});
};
// INITIALIZATION
// --------------
onDomReady(function(){
body = doc.body;
root = doc.getElementById(root) || body;
viewportWidth = viewportWidth || getViewportWidthInCssPixels();
imgSize = getSizeOfImages(breakpoints, viewportWidth, ignoreLowBandwidth);
if (!deferMode || belowfoldEnabled) {
// No defer mode: load all images now! OR
// 'belowfold' mode enabled: Load initial "above the fold" images
instance[LOADIMAGES]();
} else {
// defer mode = 'load': Load all images after window is loaded OR
// 'belowfold' not supported: 'load' fallback
onWindowReady(instance[LOADIMAGES]);
}
});
}
// PUBLIC STATIC PROPERTIES
// ------------------------
// Versioning guidelines: http://semver.org/
Riloadr.version = '1.2.0';
// PUBLIC METHODS (SHARED)
// ------------------------
/*
* The "riload" method allows you to load responsive images inserted into the
* document after the DOM is ready or after window is loaded (useful for AJAX
* content & markup created dynamically with javascript).
* Call this method after new markup is inserted into the document.
*/
Riloadr[PROTOTYPE].riload = function() {
this[LOADIMAGES](TRUE);
};
// HELPER FUNCTIONS
// ----------------
/*
* Returns the breakpoint name (image size to use).
* Uses the viewport width to mimic CSS behavior.
*/
function getSizeOfImages(breakpoints, vWidth, ignoreLowBandwidth) {
var imgSize = EMPTYSTRING
, _vWidth = vWidth
, i = 0
, breakpoint, name, minWidth, maxWidth, minDpr;
while (breakpoint = breakpoints[i]) {
name = breakpoint['name'];
minWidth = breakpoint['minWidth'];
maxWidth = breakpoint['maxWidth'];
minDpr = breakpoint['minDevicePixelRatio'];
// Viewport width found
if (vWidth > 0) {
if (minWidth && maxWidth && vWidth >= minWidth && vWidth <= maxWidth ||
minWidth && !maxWidth && vWidth >= minWidth ||
maxWidth && !minWidth && vWidth <= maxWidth) {
if (!minDpr || minDpr && devicePixelRatio >= minDpr &&
(ignoreLowBandwidth || !ignoreLowBandwidth && !hasLowBandwidth)) {
imgSize = name;
}
}
// Viewport width not found so let's find the smallest image size
// (mobile first approach).
} else if (_vWidth <= 0 || minWidth < _vWidth || maxWidth < _vWidth) {
_vWidth = minWidth || maxWidth || _vWidth;
imgSize = name;
}
i++;
}
// Cast to string
return imgSize + EMPTYSTRING;
}
/*
* Returns the layout viewport width in CSS pixels.
* To achieve a precise result the following meta must be included at least:
* <meta name="viewport" content="width=device-width">
* See:
* - http://www.quirksmode.org/mobile/viewports2.html
* - http://www.quirksmode.org/mobile/tableViewport.html
* - https://github.com/h5bp/mobile-boilerplate/wiki/The-Markup
*/
function getViewportWidthInCssPixels() {
var math = Math
, widths = [docElm.clientWidth, docElm.offsetWidth, body.clientWidth]
, screenWidthFallback = math.ceil(screenWidth / devicePixelRatio)
, l = widths[LENGTH]
, i = 0
, width;
for (; i < l; i++) {
// If not a number remove it
if (isNaN(widths[i])) {
widths.splice(i, 1);
i--;
}
}
if (widths[LENGTH]) {
width = math.max[APPLY](math, widths);
// Catch cases where the viewport is wider than the screen
if (!isNaN(screenWidthFallback)) {
width = math.min(screenWidthFallback, width);
}
}
return width || screenWidthFallback || 0;
}
/*
* Returns the URL of an image
* If reload is TRUE, a timestamp is added to avoid caching.
*/
function getImageSrc(img, base, imgSize, reload) {
var src = (img.getAttribute('data-base') || base) +
(img.getAttribute('data-src') || EMPTYSTRING);
if (reload) {
src += (QUESTION_MARK_REGEX.test(src) ? '&' : '?') +
'riloadrts='+(new Date).getTime();
}
return src.replace(BREAKPOINT_NAME_REGEX, imgSize);
}
/*
* Tells if an image is visible to the user or not.
* Thanks to jQuery
*/
function isBelowTheFold(img, foldDistance) {
var clientTop = docElm[CLIENTTOP] || body[CLIENTTOP] || 0
, clientHeight = doc.compatMode === 'CSS1Compat' && docElm[CLIENTHEIGHT] ||
body && body[CLIENTHEIGHT] || docElm[CLIENTHEIGHT];
return clientHeight <= img[GETBOUNDINGCLIENTRECT]().top - clientTop - foldDistance;
}
/*
* Tells whether user's device connection is slow or not.
* Fast connection assumed if not detected or offline.
* Based on the Network Api:
* - MDN: https://developer.mozilla.org/en/DOM/window.navigator.connection
* - W3C Working draft: http://www.w3.org/TR/netinfo-api/
* - W3C Editor's draft: http://dvcs.w3.org/hg/dap/raw-file/tip/network-api/Overview.html
* List of device bandwidths: http://en.wikipedia.org/wiki/List_of_device_bandwidths#Mobile_telephone_interfaces
*/
function hasLowBandwidth() {
var navigator = win.navigator
, connection = navigator.connection || navigator.mozConnection ||
navigator.webkitConnection || navigator.oConnection ||
navigator.msConnection || {}
, type = connection.type || 'unknown' // polyfill
, bandwidth = +connection.bandwidth || Infinity; // polyfill
// 2G, 3G and KB/s < 100 are considered slow connections.
// Offline mode is considered fast connection (bandwidth = 0 or type = none).
// According to the W3C, 'bandwidth' is reported in MB/s.
// 0.09765625 MB/s = 100 KB/s = 800 kbps. Let's round up to 0.1 MB/s.
return bandwidth > 0 && bandwidth < 0.1 || /^[23]g|3|4$/.test(type + EMPTYSTRING);
}
/*
* Thanks to underscore.js and lodash.js
* Returns a function, that, when invoked, will only be triggered at most once
* during a given window of time.
*/
function throttle(func, wait) {
var args
, result
, thisArg
, timeoutId
, lastCalled = 0;
function trailingCall() {
lastCalled = new Date;
timeoutId = NULL;
func[APPLY](thisArg, args);
}
return function() {
var now = new Date
, remain = wait - (now - lastCalled);
args = arguments;
thisArg = this;
if (remain <= 0) {
lastCalled = now;
result = func[APPLY](thisArg, args);
} else if (!timeoutId) {
timeoutId = setTimeout(trailingCall, remain);
}
return result;
};
}
/*
* Thanks to underscore.js and lodash.js
* Returns a function, that, as long as it continues to be invoked, will not
* be triggered. The function will be called after it stops being called for
* N milliseconds. If `immediate` is passed, trigger the function on the
* leading edge, instead of the trailing.
*/
function debounce(func, wait, immediate) {
var args
, result
, thisArg
, timeoutId;
function delayed() {
timeoutId = NULL;
if (!immediate) {
func[APPLY](thisArg, args);
}
}
return function() {
var isImmediate = immediate && !timeoutId;
args = arguments;
thisArg = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(delayed, wait);
if (isImmediate) {
result = func[APPLY](thisArg, args);
}
return result;
};
}
/*
* Thanks to underscore.js and lodash.js
* Defers a function, scheduling it to run after the current call stack has cleared.
*/
function defer(func) {
var args = Array[PROTOTYPE].slice[CALL](arguments, 1);
setTimeout(function(){ return func[APPLY](NULL, args); }, 1);
}
/*
* Error reporting function
*/
function error(msg) {
throw new Error( 'Riloadr: ' + msg );
}
/*
* Simple event attachment/detachment
*/
function addEvent(elem, type, fn) {
elem[add](pre + type, fn, FALSE);
}
function removeEvent(elem, type, fn) {
elem[rem](pre + type, fn, FALSE);
}
/*
* onDomReady.js 1.0 (c) 2012 Tubal Martin - MIT license
* https://github.com/tubalmartin/ondomready
* Notes:
* - Slightly adapted for Riloadr
* - Compatible with async script loading
*/
onDomReady = (function(){
var DOMContentLoaded = 'DOMContentLoaded'
, toplevel = FALSE
// Callbacks pending execution until DOM is ready
, callbacks = []
// Is the DOM ready to be used? Set to true once it occurs.
, isReady = FALSE
// The document ready event handler
, DOMContentLoadedHandler;
// Handle when the DOM is ready
function ready( fn ) {
if ( !isReady ) {
// Make sure body exists, at least, in case IE gets a little overzealous.
if ( !doc.body ) {
return defer( ready );
}
// Remember that the DOM is ready
isReady = TRUE;
// Execute all callbacks
while ( fn = callbacks.shift() ) {
defer( fn );
}
}
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( !isReady ) {
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
docElm.doScroll('left');
} catch(e) {
return defer( doScrollCheck );
}
// and execute any waiting functions
ready();
}
}
// Attach the listeners:
// Catch cases where onDomReady is called after the
// browser event has already occurred.
if ( doc[READYSTATE] === COMPLETE ) {
ready();
} else {
// W3C event model
if ( doc[ADDEVENTLISTENER] ) {
DOMContentLoadedHandler = function() {
removeEvent( doc, DOMContentLoaded, DOMContentLoadedHandler );
ready();
};
// Use the handy event callback
addEvent( doc, DOMContentLoaded, DOMContentLoadedHandler );
// IE event model
} else if ( doc[ATTACHEVENT] ) {
DOMContentLoadedHandler = function() {
if ( doc[READYSTATE] === COMPLETE ) {
removeEvent( doc, READYSTATECHANGE, DOMContentLoadedHandler );
ready();
}
};
// ensure firing before onload,
// maybe late but safe also for iframes
addEvent( doc, READYSTATECHANGE, DOMContentLoadedHandler );
// If IE and not a frame
// continually check to see if the document is ready
try {
toplevel = win.frameElement == NULL;
} catch(e) {}
if ( docElm.doScroll && toplevel ) {
doScrollCheck();
}
}
// A fallback to window.onload, that will always work
addEvent( win, LOAD, ready );
}
return function( fn ) {
// If DOM is ready, execute the function (async), otherwise wait
isReady ? defer( fn ) : callbacks.push( fn );
};
}());
/*
* Wrapper to attach load event handlers to the window
* Notes:
* - Compatible with async script loading
*/
function onWindowReady(fn) {
// Catch cases where onWindowReady is called after
// the browser event has already occurred.
if (doc[READYSTATE] === COMPLETE) {
fn();
} else {
var _fn = function() {
removeEvent(win, LOAD, _fn);
fn();
};
addEvent(win, LOAD, _fn);
}
}
return Riloadr;
});