使用背景图像的webP Jpg备份选项



我的项目使用Vue。我的很多图像都是使用背景图像完成的。

<div :style="`background:url('${user.image});`"></div>

根据谷歌,如果我正在使用我可以设置:

<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>

有没有一种方法可以对背景图像进行类似的处理?

没有真正的只支持CSS的解决方案,您必须依赖javascript。

最好的可能是有一个1x1px的webp图像,并尝试加载它,然后设置一个标志
很遗憾(?(此过程是异步的。

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>

最新更新