-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbgstyles.es6
110 lines (77 loc) · 2.62 KB
/
bgstyles.es6
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
// @ts-check
/**
* lazy image loader
* @package GZip Plugin
* @copyright Copyright (C) 2005 - 2018 Thierry Bela.
*
* dual licensed
*
* @license LGPL v3
* @license MIT License
*/
// load responsive css background images
LIB.ready(function (undef) {
// dynamic inline background images
// or Array.from()
const elements = [].slice.apply(document.querySelectorAll('[data-bg-style]'));
// responsive css background-image in [style] attribute
if (elements.length > 0) {
// or use resizeObserver
const styles = elements.map(function (el) {
return JSON.parse(el.dataset.bgStyle);
});
let keys = [];
Object.values(styles).forEach(function (entry) {
Object.keys(entry).forEach(function (value) {
value = +value;
if (keys.indexOf(value) == -1) {
keys.push(value);
}
})
});
keys.sort(function (a, b) {
return b - a;
});
function updateBgStyle() {
let i = keys.length;
let path;
let el;
let k;
let j;
let mql;
i = elements.length;
while (i--) {
el = elements[i];
k = Object.keys(styles[i]).map(key => +key).sort((a, b) => b - a);
mql = undef;
for (j = 0; j < k.length; j++) {
mql = window.matchMedia('(min-width: ' + k[j] + 'px)');
if (mql.matches) {
break;
}
}
if (mql == undef || !mql.matches || j == k.length) {
continue;
}
path = 'url(' + styles[i][k[j]] + ')';
if (el.style.backgroundImage == path) {
continue;
}
let img = new Image;
let apply = (function (src) {
return function () {
el.style.backgroundImage = src;
}
})(path);
img.src = styles[i][k[j]];
if (img.width > 0 && img.height > 0) {
apply();
} else if ('decode' in img) {
img.decode().then(apply)
} else img.onload = apply;
}
}
window.addEventListener('resize', updateBgStyle, false);
setTimeout(updateBgStyle, 25);
}
});