Modernizr: removing element with .webp in background if not support

1k Views Asked by At

I have a simple code where I'm using Modernizr.js which can help me to detect if .webp is supported in the user's browser.

I'm using this code in <head> section which can guarantee to me loading before other scripts.

I have 2 same html elements and one of them is using .webp in background second one .jpg.

Now I need to modernizr.js will detect if .webp is detected and hide an element with .jpg background. And toggle it.

For now my Javascript is not removing html element with webp background when webp is not supported.

Is there any solution how to fix it or am I using it correctly?

MY CODE:

Modernizr.on('webp', function(result) {
  if (result) {
    document.getElementsByClassName("no-webp").remove();
  } else {
    document.getElementsByClassName("webp").remove();
  }
});
section {
  height: 200px;
  width: 200px;
}

section.webp {
  background: url('http://superweb.online/assets/img/mainbg.webp') no-repeat;
  background-size: cover;
}

section.no-webp {
  background: url('http://superweb.online/assets/img/mainbg.jpg') no-repeat;
  background-size: cover;
}
<script src="http://superweb.online/assets/js/modernizr-custom.js"></script>
<section class="webp"></section>
<section class="no-webp"></section>

2

There are 2 best solutions below

0
Miloš Đakonović On

Your code:

Modernizr.on('webp', function(result) {
  if (result) {
    document.getElementsByClassName("no-webp").remove();
  } else {
    document.getElementsByClassName("webp").remove();
  }
});

is not removing element of class no-webp because the return value of getElementsByClassName method is (docs citation):

an array-like object of all child elements which have all of the given class name(s).

so, you have to decide which one of them should be removed i.e.

document.getElementsByClassName("no-webp")[0].remove(); //note the 0 index .

0
Ilijanovic On

You can use a fallback mechanism that automatically fallback to .jpg if there is no webp support with picture

<picture>
   <source srcset="http://superweb.online/assets/img/mainbg.webp" type="image/webp" />
   <img src="http://superweb.online/assets/img/mainbg.jpg" />
</picture>

The browser will automatically use the older image if there is no support. Its actually faster especially if an user has an slow internet connection.

Here is no javascript required.

apply your CSS only on the image tag