-
Notifications
You must be signed in to change notification settings - Fork 0
/
lazyfill.js
63 lines (46 loc) · 1.91 KB
/
lazyfill.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
(function () {
'use strict';
var lazyfill = function () {
function getPseudoProperty (el, context, property) {
return window.getComputedStyle(el, context).getPropertyValue(property).replace(/\"|\'/g, '');
}
var mediaControl = document.querySelector('.js-media');
if (!mediaControl) {
mediaControl = document.createElement('div');
mediaControl.className = 'js-media';
document.querySelector('body').appendChild(mediaControl);
}
var els = document.querySelectorAll('.js-lazyfill');
var media = getPseudoProperty(mediaControl, ':before', 'content');
// If no media is provided, fallback on default
if (media === '' || !media) { media = 'default'; }
// Detect changes, false by default
var changed = false;
// Loop through all the found images
for (var i = 0; i < els.length; i++) {
var el = els[i],
sources = JSON.parse(el.getAttribute('data-sources')),
src = sources[media],
srcOld = el.getAttribute('src');
if (!sources[media]) { src = sources['default']; }
if (srcOld == src) {
continue;
}
// Provide also an [alt] attribute
var alt = el.getAttribute('data-alt');
if (!alt) { alt = ''; }
el.setAttribute('src', src);
// avoid some flickering while setting [src]
el.setAttribute('alt', alt);
changed = true;
}
};
if (window.addEventListener) {
window.addEventListener("DOMContentLoaded", function () {
lazyfill();
// detach the initial event
window.removeEventListener("DOMContentLoaded", lazyfill, false);
}, false );
window.addEventListener("resize", lazyfill, false);
}
}(this));