-
Notifications
You must be signed in to change notification settings - Fork 4
/
objectfitcover.js
63 lines (49 loc) · 1.71 KB
/
objectfitcover.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 () {
var hasObjectFit = 'objectFit' in document.documentElement.style;
// add a background-image fallback
function setImages(options) {
if (hasObjectFit) {
return;
}
raf(function () {
var elements = (options && options.elements) || document.getElementsByClassName('object-fit-container');
for (var i = 0; i < elements.length; i++) {
var img = elements[i].getElementsByTagName('img')[0];
if (!img) {
console.warn('Object fit container has no image:', elements[i]);
continue;
}
// get current image src: Edge only supports 'currentSrc' for getting the current image src ('src' returns value DOM value)
var imageSrc = img.currentSrc || img.src;
elements[i].style.backgroundImage = 'url(' + imageSrc + ')';
}
});
}
window.objectFitCover = setImages;
// check for object-fit support
if(hasObjectFit) {
return;
}
// create a fallback for requestAnimationFrame
var raf = (function () {
return window.requestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 10);
};
})();
// add class to body
document.documentElement.className += ' no-object-fit';
// check when picturefill is loaded, execute it after picturefill
var checkExist = setInterval(function () {
if (window.picturefill) {
clearInterval(checkExist);
raf(setImages);
}
}, 100);
window.addEventListener('resize', function () {
// Picturefill v3.0.2 uses a 99ms timeout (https://github.com/scottjehl/picturefill/blob/master/src/picturefill.js#L1422), the resize event needs to be after that
setTimeout(function () {
setImages();
}, 100);
});
})();