-
Notifications
You must be signed in to change notification settings - Fork 14
/
picturePolyfill.js
159 lines (132 loc) · 4.53 KB
/
picturePolyfill.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
/* PicturePolyfill - Responsive Images that work today. (and mimic the proposed Picture element with span elements). Author: Andrea Verlicchi | License: MIT/GPLv2 */
(function(w) {
"use strict";
var timerId,
pixelRatio = Math.ceil(w.devicePixelRatio || 1), // The pixel density (2 is for HD aka Retina displays)
mediaQueriesSupported = w.matchMedia && w.matchMedia("only all") !== null && w.matchMedia("only all").matches;
/**
* Returns the proper src from the srcSet property
* If arrayOrString is a string, returns it
* else get the first valid element from passed position to the left
* @param arrayOrString
* @param position
* @returns {*}
*/
function getSrcFromSrcSet(arrayOrString, position) {
if (typeof arrayOrString === 'string') {
return arrayOrString;
}
while (arrayOrString[position]===undefined && position>0) {
position-=1;
}
return arrayOrString[position];
}
/**
* Loop through every element of the dataPicture array, check if the media query applies and,
* if so, get the src element from the srcSet property based depending on pixel ratio
* @param dataPicture
* @returns {string}
*/
function getSrcAttributeFromData(dataPicture) {
var media, matchedSrc;
for (var i=0, len=dataPicture.length; i<len; i+=1) {
media = dataPicture[i].media;
if (!media || w.matchMedia(media).matches) {
matchedSrc = getSrcFromSrcSet(dataPicture[i].srcset, pixelRatio-1);
}
}
return matchedSrc;
}
/**
* Search for the "standard: true" image in the array
* @param dataPicture
* @returns {string}
*/
function getStandardImageFromData(dataPicture) {
var dataElement;
for (var i=0, len=dataPicture.length; i<len; i+=1) {
dataElement = dataPicture[i];
if (dataElement.standard) {
break;
}
}
return getSrcFromSrcSet(dataElement.srcset, 0);
}
/**
* Set the src attribute of the first image element inside passed imageHolder
* if the image doesn't exist, creates it, sets its alt attribute, and appends it to imageHolder
* @param imageHolder
* @param srcAttribute
*/
function createOrUpdateImage(imageHolder, srcAttribute) {
var imageElements, imageElement;
imageElements = imageHolder.getElementsByTagName('img');
// If image already exist, use it
if (imageElements.length) {
imageElements[0].setAttribute('src', srcAttribute);
}
// Else create the image
else {
imageElement = document.createElement('img');
imageElement.setAttribute('alt', imageHolder.getAttribute('data-alt'));
imageElement.setAttribute('src', srcAttribute);
imageHolder.appendChild(imageElement);
}
}
/**
* Parses the DOM looking for elements containing the "data-picture" attribute, then
* generate the images or updates their src attribute.
* @param element the starting element to parse DOM into. If not passed, it parses the whole document.
*/
function parseDOMTree(element) {
var pictureData, imageHolder,
imageHolders = element.querySelectorAll('[data-picture]');
// Finding all the elements with data-image
for (var i=0, len=imageHolders.length; i<len; i+=1) {
imageHolder = imageHolders[i];
try {
pictureData = JSON.parse(imageHolder.getAttribute('data-picture'));
// Take the source from the matched media, or standard media
// Update the image, or create it
createOrUpdateImage(imageHolder, (mediaQueriesSupported) ?
getSrcAttributeFromData(pictureData) :
getStandardImageFromData(pictureData));
}
catch (e) {
w.console.log(e);
}
}
}
/**
* Private function to call w.picturePolyfill on the whole document
*/
function picturePolyfillDocument() {
w.picturePolyfill(document);
}
/**
* Expose the function to the global environment, if browser is supported, else empty function
* @type {Function}
*/
w.picturePolyfill = (!document.querySelectorAll) ? function(){} : function(element){
parseDOMTree(element || document);
};
/**
* Manage resize event calling the parseDOMTree function
* only if they've passed 100 milliseconds between a resize event and another
* to avoid the script to slower the browser on animated resize or browser edge dragging
*/
if (w.addEventListener) {
w.addEventListener('resize', function() {
clearTimeout(timerId);
timerId = setTimeout(picturePolyfillDocument, 100);
});
w.addEventListener('DOMContentLoaded', function(){
picturePolyfillDocument();
w.removeEventListener('load', picturePolyfillDocument);
});
w.addEventListener('load', picturePolyfillDocument);
}
else if (w.attachEvent) {
w.attachEvent('onload', picturePolyfillDocument);
}
}(this));