-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
81 lines (64 loc) · 2.1 KB
/
index.ts
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
/**
* @name webpChecker
* @author 3p-sviat
* @version 1.0.0
* @description provides functionality to check if
* the browser has webP images support and insert
* the corresponging body class as a result into. (react-apps version)
*
* @params {object} config - configuration of the watcher
* @params {boolean} config.disableGlobal - callback accepted
* @params {boolean} config.injectBodyClass - callback accepted
* @params {function} config.callback- callback accepted
* @params {string} config.imgURL - image url to test webP support
*
* @returns {function} - callback with {boolean} flag provided
*
*/
interface IWebP {
imgURL: string
callback: (status: boolean) => void
injectBodyClass: boolean
disableGlobal: boolean
}
function webPChecker(config: IWebP) {
const { imgURL = '', callback = () => {}, injectBodyClass = false, disableGlobal = false } = config || {}
const TEST_IMG = imgURL || 'https://www.gstatic.com/webp/gallery/1.webp'
function injectBodyClassByWebStatus() { // injects class `webp-support` in the `body` tag
if (!injectBodyClass) {
return
}
const bodyNode = document && document.body
bodyNode.classList.add('webp-support')
}
function addGlobalFlag(status: boolean) { // settings global variable for a whole using
if (disableGlobal) {
return
}
// @ts-ignore
window.__WEBPSUPPORT__ = status
}
function notifySubscriber(status: boolean) { // return boolean for a provided callback
if (!callback || typeof callback !== 'function') {
return
}
callback && callback(status)
}
function detectWebpSupport() {
const img = new Image()
img.src = TEST_IMG
img.onload = () => {
const isWebpSupported = !!(img.height > 0 && img.width > 0)
injectBodyClassByWebStatus()
addGlobalFlag(true)
notifySubscriber(isWebpSupported)
}
img.onerror = (e) => {
addGlobalFlag(false)
notifySubscriber(false)
console.log('Some error is happen during webP support checking:', JSON.stringify(e))
}
}
detectWebpSupport()
}
export default webPChecker