Last active
May 15, 2021 20:29
-
-
Save ayoola-solomon/7b1282d6a3ddf26b91f496967a689b57 to your computer and use it in GitHub Desktop.
react hook to check webp support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://developers.google.com/speed/webp/faq#how_can_i_detect_browser_support_for_webp | |
// 'callback(feature, result)' will be passed back the detection result (in an asynchronous way!) | |
export const checkWebPSupport = callback => { | |
const kTestImages = { | |
lossy: 'UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA' | |
} | |
const img = new Image() | |
img.onload = () => { | |
const result = img.width > 0 && img.height > 0 | |
callback(result) | |
} | |
img.onerror = function() { | |
callback(false) | |
} | |
img.src = 'data:image/webp;base64,' + kTestImages.lossy | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react' | |
import { checkWebPSupport } from './checkWebPSupport' | |
export const useWebP = () => { | |
const [supported, setSupported] = useState(false) | |
useEffect(() => { | |
checkWebPSupport(result => { | |
setSupported(result) | |
}) | |
}, []) | |
return supported | |
} |
This is amazing, however... it makes react render the src-attribute of my images twice,
once with jpg and once with webp.
how ?
Because onload is async. So supported is "false" ... and then the Effect ties to determine if WebP is supported.
and then supported is "true". so the src of the image switches.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is amazing, however... it makes react render the src-attribute of my images twice,
once with jpg and once with webp.