[Vuejs]-Jpg backup option for webP using Background-image?

6👍

There is no truly CSS only solution, you’d have to rely on javascript for this.

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

Leave a comment