Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

webp for background-image #52

Closed
pabloow opened this issue Dec 24, 2018 · 2 comments
Closed

webp for background-image #52

pabloow opened this issue Dec 24, 2018 · 2 comments

Comments

@pabloow
Copy link

pabloow commented Dec 24, 2018

How can I achieve something similar to:

'<source srcSet={require('./images/my-image.jpg?webp')} type="image/webp" /><source srcSet={require('./images/my-image.jpg')} type="image/jpeg" /><img src={require('./images/my-image.jpg')} />'

for a background-image? Is it currently possible?

@cyrilwanner
Copy link
Owner

cyrilwanner commented Jan 10, 2019

Hi @pabloow
Sorry for the late response, I didn't have much time in the last few weeks.

Unfortunately, it is not possible with pure CSS.
The most suggested workaround is to detect if your browser supports WebP in JavaScript (e.g. with Modernizr) and then add, for example, a .webp class to your body.
In the CSS you can then use the correct image type like this:

body.webp .mydiv {
  background-image: url('./images/my-image.jpg?webp');
}
body:not(.webp) .mydiv {
  background-image: url('./images/my-image.jpg');
}

Examples are from https://stackoverflow.com/questions/47607201/webp-image-fall-back and https://css-tricks.com/using-webp-images/

In react, you could also have a helper function and then choose the correct classname:

import { supportsWebp } from './helpers'

export default () => (
	<div className={supportsWebp() ? 'webp-bg' : 'fallback-bg'}>
		...
	</div>
);

I hope that this helps you in this topic :)

@pabloow
Copy link
Author

pabloow commented Jan 14, 2019

@cyrilwanner thank you :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants