Skip to content

Instantly share code, notes, and snippets.

@ayoola-solomon
Last active May 15, 2021 20:29
Show Gist options
  • Save ayoola-solomon/7b1282d6a3ddf26b91f496967a689b57 to your computer and use it in GitHub Desktop.
Save ayoola-solomon/7b1282d6a3ddf26b91f496967a689b57 to your computer and use it in GitHub Desktop.
react hook to check webp support
// 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
}
import { useState, useEffect } from 'react'
import { checkWebPSupport } from './checkWebPSupport'
export const useWebP = () => {
const [supported, setSupported] = useState(false)
useEffect(() => {
checkWebPSupport(result => {
setSupported(result)
})
}, [])
return supported
}
@Kyoss79
Copy link

Kyoss79 commented May 4, 2021

This is amazing, however... it makes react render the src-attribute of my images twice,
once with jpg and once with webp.

@ayoola-solomon
Copy link
Author

This is amazing, however... it makes react render the src-attribute of my images twice,
once with jpg and once with webp.

how ?

@Kyoss79
Copy link

Kyoss79 commented May 15, 2021

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