使用Background-image的webP的jpg备份选项? [英] Jpg backup option for webP using Background-image?
本文介绍了使用Background-image的webP的jpg备份选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为我的项目使用Vue.我的很多图像都是使用背景图像完成的.
I am using Vue for my project. A lot of my images are done using background-image.
<div :style="`background:url('${user.image});`"></div>
根据Google的说明,如果我使用的是我可以设置的内容:
According to google if I am using an I can setup:
<picture>
<source srcset="img/awesomeWebPImage.webp" type="image/webp">
<source srcset="img/creakyOldJPEG.jpg" type="image/jpeg">
<img src="img/creakyOldJPEG.jpg" alt="Alt Text!">
</picture>
有没有办法为背景图片做类似的事情?
Is there a way to do something similar for background-image?
推荐答案
没有真正的CSS唯一解决方案,您必须依靠javascript.
There is no truly CSS only solution, you'd have to rely on javascript for this.
最好是使用1x1px的webp图像,然后尝试加载它然后设置一个标志.
不幸的是(?)此过程是异步的.
The best is probably to have a 1x1px webp image and try to load it to then set a flag.
Unfortunately (?) this process is asynchronous.
function testWebPSupport() {
return new Promise( (resolve) => {
const webp = "data:image/webp;base64,UklGRkAAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAIAAAAAAFZQOCAYAAAAMAEAnQEqAQABAAFAJiWkAANwAP79NmgA";
const test_img = new Image();
test_img.src = webp;
test_img.onerror = e => resolve( false );
test_img.onload = e => resolve( true );
} );
}
(async ()=> {
const supports_webp = await testWebPSupport();
console.log( "this browser supports webp images:", supports_webp );
// for stylesheets
if( !supports_webp ) {
document.body.classList.add( 'no-webp' );
}
// for inline ones, just check the value of supports_webp
const extension = supports_webp ? 'webp' : 'jpg';
// elem.style.backgroundImage = `url(file_url.${ extension })`;
})();
.bg-me {
width: 100vw;
height: 100vh;
background-image: url(https://upload.wikimedia.org/wikipedia/commons/9/98/Great_Lakes_from_space_during_early_spring.webp);
background-size: cover;
}
.no-webp .bg-me {
/* fallback to png */
background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Great_Lakes_from_space_during_early_spring.webp/800px-Great_Lakes_from_space_during_early_spring.webp.png);
}
<div class="bg-me"></div>
这篇关于使用Background-image的webP的jpg备份选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文