[使用背景图像的WebP的Jpg备份选项?

问题描述 投票:0回答:1

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

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

根据google,如果我使用的是我可以设置的内容:

<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 google-chrome vue.js webp
1个回答
1
投票

没有真正的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>
© www.soinside.com 2019 - 2024. All rights reserved.