-
Notifications
You must be signed in to change notification settings - Fork 5
/
srcset-polyfill.js
52 lines (40 loc) · 1.63 KB
/
srcset-polyfill.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
(function(window, document) {
// Test if it already supports srcset
if ('srcset' in document.createElement('img'))
return true;
// We want to get the device pixel ratio
var maxWidth = (window.innerWidth > 0) ? window.innerWidth : screen.width,
maxHeight = (window.innerHeight > 0) ? window.innerHeight : screen.height,
maxDensity = window.devicePixelRatio || 1;
// Implement srcset
function srcset(image) {
if (!image.attributes['srcset']) return false;
var candidates = image.attributes['srcset'].nodeValue.split(',');
for (var i = 0; i < candidates.length; i++) {
// The following regular expression was created based on the rules
// in the srcset W3C specification available at:
// http://www.w3.org/html/wg/drafts/srcset/w3c-srcset/
var descriptors = candidates[i].match(
/^\s*([^\s]+)\s*(\s(\d+)w)?\s*(\s(\d+)h)?\s*(\s(\d+)x)?\s*$/
),
filename = descriptors[1],
width = descriptors[3] || false,
height = descriptors[5] || false,
density = descriptors[7] || 1;
if (width && width < maxWidth) {
continue;
}
if (height && height < maxHeight) {
continue;
}
if (density && density > maxDensity) {
continue;
}
image.src = filename;
}
}
var images = document.getElementsByTagName('img');
for (var i=0; i < images.length; i++) {
srcset(images[i]);
}
})(window, document);